Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
    }
}
like image 664
HasanChute Avatar asked Dec 17 '22 17:12

HasanChute


2 Answers

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.

like image 185
Kaushik Makwana Avatar answered May 10 '23 14:05

Kaushik Makwana


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

like image 32
Hitesh Borse Avatar answered May 10 '23 14:05

Hitesh Borse