MapKit zoom to user current location

后端 未结 8 528
慢半拍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条回答
  •  情话喂你
    2021-02-01 18:36

    In Swift 4.2 there has been changes with this code. Here is how it works now:

    import UIKit
    import MapKit
    import CoreLocation
    
    class MapVC: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
    
        @IBOutlet weak var mapView: MKMapView!
        var locationManager = CLLocationManager()
        let authorizationStatus = CLLocationManager.authorizationStatus()
        let regionRadius: Double = 1000
    
        override func viewDidLoad() {
            super.viewDidLoad()
            mapView.delegate = self
            locationManager.delegate = self
            configureLocationServices()
        }
    
        func centerMapOnUserLocation() {
            guard let coordinate = locationManager.location?.coordinate else {return}
            let coordinateRegion = MKCoordinateRegion(center: coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
            mapView.setRegion(coordinateRegion, animated: true)
        }
    
        func configureLocationServices() {
            if authorizationStatus == .notDetermined {
                locationManager.requestAlwaysAuthorization()
            } else {
                return
            }
        }
    
        func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
            centerMapOnUserLocation()
        }
    
    }
    

提交回复
热议问题