Show Current Location and Update Location in MKMapView in Swift

前端 未结 10 1456
爱一瞬间的悲伤
爱一瞬间的悲伤 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:55

    100% working, easy steps and tested

    Import libraries:

    import MapKit
    import CoreLocation
    

    set delegates:

    CLLocationManagerDelegate,MKMapViewDelegate
    

    Take variable:

    let locationManager = CLLocationManager()
    

    write this code on viewDidLoad():

    self.locationManager.requestAlwaysAuthorization()
    
        // For use in foreground
        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 = MKCoordinateSpanMake(0.05, 0.05)
        let region = MKCoordinateRegion(center: locValue, span: span)
        mapView.setRegion(region, animated: true)
    
        let annotation = MKPointAnnotation()
        annotation.coordinate = locValue
        annotation.title = "Javed Multani"
        annotation.subtitle = "current location"
        mapView.addAnnotation(annotation)
    
        //centerMap(locValue)
    }
    

    Do not forgot to set permission in info.plist

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

    It's look like:

提交回复
热议问题