HasanChute
HasanChute

Reputation: 61

How to show location on map view on swift? I believe my code is current but simulator doesn't show location or the blue dot?

I am trying to show on my current location and a blue dot on the map using the map view on swift. However it does not show my location nor the blue dot I'm very positive of my code but I can't get it to show! it's probably an issue with the settings?

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController {

    @IBOutlet weak var mapView: MKMapView!

    let locationManager = CLLocationManager()
    let regionInMeters: Double = 1000

    override func viewDidLoad() {
        super.viewDidLoad()
        checkLocationServices()
    }


    func setupLocationManager() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    }


    func centerViewOnUserLocation() {
        if let location = locationManager.location?.coordinate {
            let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
            mapView.setRegion(region, animated: true)
        }
    }
    func checkLocationServices() {
        if CLLocationManager.locationServicesEnabled() {
            setupLocationManager()
            checkLocationAuthorrization()
        } else {
            // Show alert letting the user know they have to turn this on.
        }
    }


    func checkLocationAuthorrization() {
        switch CLLocationManager.authorizationStatus() {
        case .authorizedWhenInUse:
            mapView.showsUserLocation = true
            centerViewOnUserLocation()
            locationManager.startUpdatingLocation()
            break
        case .denied:
            // Show alret instructing them how to turn on permissions
            break
        case .notDetermined:
            break
        case .restricted:
            // Show alret letting them know what's up
            break
        case .authorizedAlways:
            break
        }
    }
}




extension ViewController: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion.init(center: center, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
        mapView.setRegion(region, animated: true)
    }


    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        checkLocationAuthorrization()
    }
}

Upvotes: 5

Views: 8928

Answers (6)

Greeshma K P
Greeshma K P

Reputation: 1

import UIKit
import MapKit

class ViewController: UIViewController {

   @IBOutlet weak var mapview: MKMapView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let location = CLLocationCoordinate2D(latitude: "", longitude: "")
        let span = MKCoordinateSpanMake(0.5, 0.5)
        let region = MKCoordinateRegion(center: location, span: span)
        mapview.setRegion(region, animated: true)
        
        let annotation = MKPointAnnotation()
        annotation.coordinate = location
        annotation.title = "your title"
        mapview.addAnnotation(annotation)
    }

Upvotes: 0

Hitesh Borse
Hitesh Borse

Reputation: 479

To show user location on map do following steps:

try this path- Go to product->Edit Scheme->Options->select Allow Location simulation and select default location. Here You can also add custom location using GPX file. After setting clean and run the app.

enter image description here

Upvotes: 2

Shah Nilay
Shah Nilay

Reputation: 798

In your viewDidLoad method please write the below code.
Default value of showsUserLocation is false. So, we have to update it's default value.

override func viewDidLoad() {
        super.viewDidLoad()
        self.mapView.showsUserLocation = true
        checkLocationServices()
    }

Refer my updated code.

Upvotes: 0

Kaushik Makwana
Kaushik Makwana

Reputation: 1327

You have to add below permission in Info.plist file

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Usage Description</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>Usage Description</string>

<key>NSLocationWhenInUseUsageDescription</key>
<string>Usage Description</string>

Import libraries:

import MapKit
import CoreLocation

Set delegates:

CLLocationManagerDelegate,MKMapViewDelegate

Add variable:

private var locationManager: CLLocationManager!
private var currentLocation: CLLocation?

write below code on viewDidLoad():

    mapView.delegate = self
    mapView.showsUserLocation = true
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest

    // Check for Location Services
    if CLLocationManager.locationServicesEnabled() {
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

Write delegate method for location:

   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 = MKCoordinateRegion(center: userLocation.coordinate, latitudinalMeters: 2000, longitudinalMeters: 2000)
            mapView.setRegion(viewRegion, animated: false)
        }
    }
}

Thats all, Now you able to see your current location and blue dot.

Upvotes: 8

AamirR
AamirR

Reputation: 12218

The problem seems to be in method checkLocationAuthorrization, here you have to ask for locationManager.requestWhenInUseAuthorization() when the status is notDetermined, like so:

func checkLocationAuthorization(authorizationStatus: CLAuthorizationStatus? = nil) {
    switch (authorizationStatus ?? CLLocationManager.authorizationStatus()) {
    case .authorizedAlways, .authorizedWhenInUse:
        locationManager.startUpdatingLocation()
        mapView.showsUserLocation = true
    case .restricted, .denied:
        // show alert instructing how to turn on permissions
        print("Location Servies: Denied / Restricted")
    case .notDetermined:
        locationManager.requestWhenInUseAuthorization()
    }
}

Also change the delegate method to pass the current status received

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    self.checkLocationAuthorization(authorizationStatus: status)
}

Also note that locationManager.requestWhenInUseAuthorization() will not work, if Info.plist does not have following usage description(s), so edit the Info.plist file and make sure:

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Message for AlwaysAndWhenInUseUsageDescription</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>Message for AlwaysUsageDescription</string>

<key>NSLocationWhenInUseUsageDescription</key>
<string>Message for WhenInUseUsageDescription</string>

Finally, you got to wait for an location update to call centerViewOnUserLocation, like so

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location = locations.last else { return }

    let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
    let region = MKCoordinateRegion(center: location.coordinate, span: span)
    mapView.setRegion(region, animated: true)
}

Upvotes: 1

Huned
Huned

Reputation: 74

Simulator doesn't show current location but you can manually add a location in it by:

Debug -> Location -> Custom Location and then give coordinates.

Upvotes: 0

Related Questions