MapKit zoom to user current location

后端 未结 8 534
慢半拍i
慢半拍i 2021-02-01 17:59

I am trying to simply show user\'s location on the map, but I need to when app launches, the map should zoom to current location ,but I don\'t know why map doesn\'t zoom at all

8条回答
  •  旧时难觅i
    2021-02-01 18:35

    I faced similar issue and wasted 4 days thinking whats going wrong. Finally resolved with creating these lines of code in viewDidLoad Method :

        //Zoom to user location
        let noLocation = CLLocationCoordinate2D()
        let viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 200, 200)
        mapView.setRegion(viewRegion, animated: false)
        mapView.showsUserLocation = true
    

    In ViewDidLoad Method add these new changes code :

    override func viewDidLoad() {
    
        super.viewDidLoad()
    
        let locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    
        // Check for Location Services
        if (CLLocationManager.locationServicesEnabled()) {
            locationManager.requestAlwaysAuthorization()
            locationManager.requestWhenInUseAuthorization()
        }
    
        //Zoom to user location
        if let userLocation = locationManager.location?.coordinate {
            let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation, 200, 200)
            mapView.setRegion(viewRegion, animated: false)
        }
    
        self.locationManager = locationManager
    
        DispatchQueue.main.async {
            self.locationManager.startUpdatingLocation()
        }
    
    }
    

    Hope this helps to resolve your issue. Feel free to post comment if any further issue. Thanks

提交回复
热议问题