In iOS, using Swift, I want to show the user's location, but the blue dot does not appear on the MapView

875 views Asked by At

The blue dot does not appear on the map. It appears there is some disconnect between the CLLocation manager and the self.mapView.userLocation.coordinate value.

The CLLocation manager correctly returns the Apple Campus coordinates, but the mapView.userLocation.coordinate value returns 0,0 for both latitude and longitude.

I have debugged this for hours and hours.

More Information Below:

In viewDidAppear and viewDidLoad, I printed the user's current location to the console as follows:

print(self.mapView.userLocation.coordinate)

This is the output that is rendered in the console:

CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)

This is what my MapViewController looks like:

import UIKit
import CoreLocation
import MapKit

class MapViewController: UIViewController, MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!
var manager: CLLocationManager? = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()

    // map stuff
    manager?.delegate = self
    manager?.desiredAccuracy = kCLLocationAccuracyBest
    self.mapView.delegate = self

    // print user's current location to console
    print("user location in view did load:")
    print(self.mapView.userLocation.coordinate)

}

override func viewDidAppear(_ animated: Bool) {
    manager?.requestAlwaysAuthorization()
    manager?.startUpdatingLocation()

    self.mapView.showsUserLocation = true
    self.mapView.userTrackingMode = .follow

    // print user's current location to console
    print("user location in view did appear:")
    print(self.mapView.userLocation.coordinate)

    animateMapToUserLocation()
}

}

Notes:

  1. I have added the relevant Privacy messages to the Info.plist file.

  2. The MapView in the storyboard is connected, with a solid circle, to the correct ViewController.

  3. The MapViewController is instantiated as follows:

    let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) let mapVC = storyboard.instantiateViewController(withIdentifier: "MapVC") as? MapViewController self.present(mapVC!, animated: true, completion: nil)

2

There are 2 answers

0
RedEye On

My control flow was off. The map would render before the app had permission to retrieve the user location. It is working now.

0
Kosuke Ogawa On

Have you implemented the viewForAnnotation function? are you checking that you're not drawing (or failing to draw) a different sort of pin for the MKUserLocation?

e.g.

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }
    ...
}

Check also Settings > Privacy > Location Services > Your app

enter image description here