获取用户位置并创建不同步的地图

时间:2015-06-14 06:35:46

标签: ios swift mapbox

以下代码是获取用户当前位置并创建地图集地图。 问题是在获取用户位置之前正在创建地图箱地图。 我怎么能减慢或同步这个过程? 提前谢谢你,

  import UIKit
  import CoreLocation
  import MapboxGL

 class AViewController: UIViewController, CLLocationManagerDelegate {
   var manager:CLLocationManager!
   var userLocation:CLLocation = CLLocation(latitude: 25.776243, longitude: -80.136509)

override func viewDidLoad() {
    super.viewDidLoad()

    println("inside viewdidload")
    self.getUserLocation()
}//eom

override func viewDidAppear(animated: Bool) {
    println("inside viewdidappear")
   self.createMapBoxMap()
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


/*** MapBox Functions ************************************************************************/
    /*Create preliminary map */
    func createMapBoxMap(){
        // set your access token
        let mapView = MGLMapView(frame: view.bounds, accessToken: "pk.eyJ1IjoiZGFya2ZhZGVyIiwiYSI6IlplVDhfR3MifQ.pPEz732qS8g0WEScdItakg")

        mapView.autoresizingMask = .FlexibleWidth | .FlexibleHeight

        // set the map's center coordinate
        mapView.setCenterCoordinate(CLLocationCoordinate2D(latitude: self.userLocation.coordinate.latitude, longitude: self.userLocation.coordinate.longitude),
            zoomLevel: 13, animated: false)
        view.addSubview(mapView)

        //showing the user location on map - blue dot
        mapView.showsUserLocation = true
    }//eom


/*** location Functions ************************************************************************/
    /*getting user current location*/
    func getUserLocation(){
        self.manager = CLLocationManager()
        self.manager.delegate = self
        self.manager.desiredAccuracy = kCLLocationAccuracyBest
        self.manager.requestWhenInUseAuthorization()
        self.manager.startUpdatingLocation()
    }//eom

    /*location manager 'didUpdateLocations' function */
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        self.manager.stopUpdatingLocation() //stop getting user location
        println(locations)

        self.userLocation = locations[0] as! CLLocation

    }//eom

    /* errors occurred */
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError) {
        println("Error:" + error.localizedDescription)
    }//eom

} // EOC

1 个答案:

答案 0 :(得分:1)

位置管理器异步运行(预期行为),这意味着它会立即返回并在调用create map box方法后立即完成创建映射。但是,这并不意味着地图已经到了位置。我认为实现这一点的最佳方法是将self.createMapBoxMap()移至didUpdateLocations内并尝试。根据我的经验,您希望通过这样的异步方法在回调中创建视图。您可能希望拥有某种类型的加载视图,因为用户最初会感到困惑。