Making the map zoom to user location and annotation (swift 2)

两盒软妹~` 提交于 2019-11-30 13:07:10

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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!