MapKit zoom to user current location

后端 未结 8 512
慢半拍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()
        }
    
    }
    
    0 讨论(0)
  • 2021-02-01 18:37

    Try with MKMapViewDelegate func:

    var isInitiallyZoomedToUserLocation: Bool = false 
    
    func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
        if !isInitiallyZoomedToUserLocation {
           isInitiallyZoomedToUserLocation = true
           mapView.showAnnotations([userLocation], animated: true)
        }
    }
    
    0 讨论(0)
提交回复
热议问题