我想在启动时显示用户的当前位置,然后继续跟踪他们的位置,但不要以当前位置为中心。我的想法是以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)
}
答案 0 :(得分:0)
// MARK: - 位置lattitude longtitude方法委托方法
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
if locationManager.location != nil
{
let locValue = (locationManager.location?.coordinate)!
lat = locValue.latitude
long = locValue.longitude
}
}
答案 1 :(得分:0)
您只需在初始化animateMap(currentLocation!)
的委托方法didUpdateLocations
中调用currentLocation
函数。
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
currentLocation = locations.last!
animateMap(currentLocation!)
//Either Call `stopUpdatingLocation()`
locationManager.stopUpdatingLocation()
//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
答案 2 :(得分:0)
在didUpdateLocations委托方法中调用animateMap函数,而不是在viewDidLoad中调用。并且,允许地图仅在第一次居中。你可以为它做一些bool变量。
var isLocationUpdated = false
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
currentLocation = locations.last!
if (!isLocationUpdated)
{
animateMap(currentLocation!)
isLocationUpdated = true
}
}