User Interaction is unavailable while mapkit.setRegion is set

56 Views Asked by At
import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var mapKitView: MKMapView!
    var locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        mapKitView.delegate = self
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = CLLocationCoordinate2D(latitude: locations[0].coordinate.latitude, longitude: locations[0].coordinate.longitude)
        let span = MKCoordinateSpan(latitudeDelta: 0.001, longitudeDelta: 0.001)
        let region = MKCoordinateRegion(center: location, span: span)
        mapKitView.setRegion(region, animated: true)
    } 
    
    
}

mapKitView.setRegion(region, animated: true) is blocking User Interaction in mapkit and I can't zooming, scrolling and rotating

1

There are 1 best solutions below

0
alobaili On

It seems from the code that you are trying to keep the map centered on the user's location. To do this while preserving user interaction it's better to delete the line:

mapKitView.setRegion(region, animated: true)

and instead set the userTrachingMode property on mapKitView to .follow or .followWithHeading.

with this, the map's visible region will follow the user as the location updates.

Here's the documentation of the userTrackingMode property on MKMapView: https://developer.apple.com/documentation/mapkit/mkmapview/1616208-usertrackingmode