如何检查locationManager是否已更新当前位置?

3

我希望在应用启动时展示用户的当前位置,并持续跟踪他们的位置,但不再以当前位置为中心。我的想法是在viewDidLoad()中以当前位置为中心,但我不知道如何等待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)
}
3个回答

0

// 标记:位置纬度经度方法委托方法

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

0
你只需要在初始化currentLocation的地方,在delegate方法didUpdateLocations中调用animateMap(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

但是这样做也会在每次位置更新时调用animateMap,它会将地图居中于当前位置,对吗?我不希望这种情况发生。我只想在启动时将地图居中于当前位置。 - Asteria
@Asteria 然后你可以停止位置管理器的更新,或者你可以创建一个布尔类型的实例属性来适应你的需求。 - Nirav D
这样做就可以了。谢谢! - Asteria

0
在didUpdateLocations委托方法中调用animateMap函数,而不是在viewDidLoad中调用。并且,只允许地图在第一次时居中。你可以使用一个布尔变量来实现这个功能。
var isLocationUpdated = false 

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

是的,你做了一样的事情。我在发表我的答案之后才看到你的回答。 - MBN

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接