Show Current Location and Update Location in MKMapView in Swift

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

    For swift 3 and XCode 8 I find this answer:

    • First, you need set privacy into info.plist. Insert string NSLocationWhenInUseUsageDescription with your description why you want get user location. For example, set string "For map in application".

    • Second, use this code example

      @IBOutlet weak var mapView: MKMapView!
      
      private var locationManager: CLLocationManager!
      private var currentLocation: CLLocation?
      
      override func viewDidLoad() {
          super.viewDidLoad()
      
          mapView.delegate = self
      
          locationManager = CLLocationManager()
          locationManager.delegate = self
          locationManager.desiredAccuracy = kCLLocationAccuracyBest
      
          // Check for Location Services
      
          if CLLocationManager.locationServicesEnabled() {
              locationManager.requestWhenInUseAuthorization()
              locationManager.startUpdatingLocation()
          }
      }
      
      // MARK - CLLocationManagerDelegate
      
      func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
          defer { currentLocation = locations.last }
      
          if currentLocation == nil {
              // Zoom to user location
              if let userLocation = locations.last {
                  let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000)
                  mapView.setRegion(viewRegion, animated: false)
              }
          }
      }
      
    • Third, set User Location flag in storyboard for mapView.

    0 讨论(0)
  • 2020-12-02 12:44

    MyLocation is a Swift iOS Demo.

    You can use this demo for the following:

    1. Show the current location.

    2. Choose other location: in this case stop tracking the location.

    3. Add a push pin to a MKMapView(iOS) when touching.

    0 讨论(0)
  • 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 *

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>This application requires location services to work</string>
    
    <key>NSLocationAlwaysUsageDescription</key>
    <string>This application requires location services to work</string>
    
    0 讨论(0)
  • 2020-12-02 12:50

    You have to override CLLocationManager.didUpdateLocations (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last{
            let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
            let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
            self.map.setRegion(region, animated: true)
        }
    }
    

    NOTE: If your target is iOS 8 or above, you must include the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key in your Info.plist to get the location services to work.

    0 讨论(0)
  • 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

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>This application requires location services to work</string>
    
    <key>NSLocationAlwaysUsageDescription</key>
    <string>This application requires location services to work</string>
    

    It's look like:

    0 讨论(0)
  • 2020-12-02 12:55

    You just need to set the userTrackingMode of the MKMapView. If you only want to display and track the user location and implement the same behaviour as the Apple Maps app uses, there is no reason for writing additional code.

    mapView.userTrackingMode = .follow
    

    See more at https://developer.apple.com/documentation/mapkit/mkmapview/1616208-usertrackingmode .

    0 讨论(0)
提交回复
热议问题