user
user

Reputation: 445

Swift 4 map not showing users current location

I'm trying to show the users current location on the map but nothing is working. Where am I going wrong?

import UIKit
import CoreLocation
import MapKit

class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    var window: UIWindow?
    var mapView: MKMapView?
    let locationManager = CLLocationManager()

    let distanceSpan: Double = 500

    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavBar()
        setupMapView()
        setupLocationManager()
    }

    fileprivate func setupNavBar() {
        self.navigationItem.title = "Near By"
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .done, target: self, action: #selector(handleDissmiss))
    }

    fileprivate func setupLocationManager() {self.locationManager.requestWhenInUseAuthorization()

        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
        }

    }

    fileprivate func setupMapView() {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.view.backgroundColor = UIColor.white
        self.mapView?.showsUserLocation = true
        self.mapView = MKMapView(frame: CGRect(x: 0, y: 20, width: (self.window?.frame.width)!, height: view.frame.height))
        self.view.addSubview(self.mapView!)
    }

Upvotes: 1

Views: 84

Answers (1)

patroclus974
patroclus974

Reputation: 474

You are setting the showUserLocation property before allocating your mapView.

In the future, to avoid this kind of mistake, you can use a different coding style where you don't use optional e.g.

 fileprivate func setupMapView() {
    let mView = MKMapView(frame: CGRect(x: 0, y: 20, width: view.frame.width, height: view.frame.height))
    mView.showsUserLocation = true
    view.addSubview(mView)
    self.mapView = mView
}

In addition, make sure your Info.plist contains the NSLocationWhenInUseUsageDescription key - as documented https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html

Upvotes: 2

Related Questions