Show Current Location and Update Location in MKMapView in Swift

前端 未结 10 1470
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 12:06

I am learning how to use the new Swift language (only Swift, no Objective-C). To do it, I want to do a simple view with a map (MKMapView). I want to find and up

10条回答
  •  清歌不尽
    2020-12-02 12:44

    Swift 5.1

    Get Current Location and Set on MKMapView

    Import libraries:

    import MapKit
    import CoreLocation
    

    set delegates:

    CLLocationManagerDelegate , MKMapViewDelegate
    

    Declare variable:

    let locationManager = CLLocationManager()
    

    Write this code on viewDidLoad():

    self.locationManager.requestAlwaysAuthorization()
    self.locationManager.requestWhenInUseAuthorization()
    
    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    }
    mapView.delegate = self
    mapView.mapType = .standard
    mapView.isZoomEnabled = true
    mapView.isScrollEnabled = true
    
    if let coor = mapView.userLocation.location?.coordinate{
        mapView.setCenter(coor, animated: true)
    }
    

    Write delegate method for location:

    func locationManager(_ manager: CLLocationManager, didUpdateLocations 
        locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
    
        mapView.mapType = MKMapType.standard
    
        let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
        let region = MKCoordinateRegion(center: locValue, span: span)
        mapView.setRegion(region, animated: true)
    
        let annotation = MKPointAnnotation()
        annotation.coordinate = locValue
        annotation.title = "You are Here"
        mapView.addAnnotation(annotation)
    }
    

    Set permission in info.plist *

    NSLocationWhenInUseUsageDescription
    This application requires location services to work
    
    NSLocationAlwaysUsageDescription
    This application requires location services to work
    

提交回复
热议问题