I am working with mapkit. I want the map to zoom to show the user\'s location and the annotated point, instead of just zooming to the user\'s current location.
Curre
It just jumps right back to the user's location, because didUpdateLocations
method is called many times. There are two solutions.
1) Use requestLocation
If you use requestLocation
method instead of startUpdatingLocation
, didUpdateLocations
method is called only once
if #available(iOS 9.0, *) {
locationManager.requestLocation()
} else {
// Fallback on earlier versions
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLoction: CLLocation = locations[0]
let latitude = userLoction.coordinate.latitude
let longitude = userLoction.coordinate.longitude
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
self.map.setRegion(region, animated: true)
self.map.showsUserLocation = true
}
2) Use flag
var isInitialized = false
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if !isInitialized {
// Here is called only once
isInitialized = true
let userLoction: CLLocation = locations[0]
let latitude = userLoction.coordinate.latitude
let longitude = userLoction.coordinate.longitude
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
self.map.setRegion(region, animated: true)
self.map.showsUserLocation = true
}
}