简体   繁体   中英

How do you set MKMapView region on current location and follow user location?

I have a button that centers the map and sets the region based on the user's current location and then sets the user tracking mode to follow. I am following the user while moving and if they move the map or zoom out it sets the user tracking mode to none.

This is what I have

guard let currentLocation = locationManager.location else { return }
let coordinateRegion = MKCoordinateRegion(center: currentLocation.coordinate,
                                          latitudinalMeters: regionRadius,
                                          longitudinalMeters: regionRadius)
map.setRegion(coordinateRegion, animated: true)
map.setUserTrackingMode(MKUserTrackingMode.follow, animated: true)

It successfully sets the region back to the user's current location and then the user tracking mode to follow but for some reason it doesn't follow anymore.

You need to wait for setRegion animation to finish so it doesn't mess with setUserTrackingMode.

guard let currentLocation = locationManager.location else { return }
let coordinateRegion = MKCoordinateRegion(center: currentLocation.coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)

MKMapView.animate(withDuration: 0.5, animations: {
    self.map.setRegion(coordinateRegion, animated: true)
}) { _ in
    self.map.setUserTrackingMode(MKUserTrackingMode.follow, animated: false)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM