Как отобразить местоположение при просмотре карты в Swift? Я считаю, что мой код является текущим, но симулятор не показывает местоположение или синюю точку?

#ios #swift #mapkit #core-location

#iOS #swift #mapkit #core-location

Вопрос:

Я пытаюсь отобразить свое текущее местоположение и синюю точку на карте, используя просмотр карты в swift. Однако он не показывает ни мое местоположение, ни синюю точку, я очень уверен в своем коде, но я не могу заставить его отображаться! вероятно, это проблема с настройками?

 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()
    }
}
  

Комментарии:

1. В меню выберите Debug -> Location -> Custom location и введите свои координаты

2. Добавьте LocationManager.requestWhenInUseAuthorization() в метод setupLocationManager

3. сначала для вашей карты установите self.MapView.showsUserLocation = true и после запуска приложения Debug -> Location -> введите пользовательское местоположение или выберите его из списка

4. Я получил это сообщение об ошибке после того, как я добавил его [11334: 14070810] Неустранимая ошибка: неожиданно найдено nil при неявном развертывании необязательного значения

5. добавьте точку останова исключения и проверьте, где происходит сбой

Ответ №1:

Вы должны добавить разрешение ниже в Info.plist файл

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

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

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

Импорт библиотек:

 import MapKit
import CoreLocation
  

Установить делегаты:

 CLLocationManagerDelegate,MKMapViewDelegate
  

Добавить переменную:

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

напишите ниже код на 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()
    }
  

Напишите метод делегирования для местоположения:

    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)
        }
    }
}
  

Вот и все, теперь вы можете видеть свое текущее местоположение и синюю точку.

Ответ №2:

Чтобы отобразить местоположение пользователя на карте, выполните следующие действия:

попробуйте этот путь — Перейдите к продукту-> Редактировать схему-> Параметры-> выберите Разрешить моделирование местоположения и выберите местоположение по умолчанию. Здесь вы также можете добавить пользовательское местоположение с помощью файла GPX. После настройки очистите и запустите приложение.

введите описание изображения здесь

Комментарии:

1. к сожалению, по-прежнему нет синей точки или моего местоположения

Ответ №3:

Проблема, похоже, в методе checkLocationAuthorrization , здесь вы должны запросить, locationManager.requestWhenInUseAuthorization() когда статус notDetermined , вот так:

 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()
    }
}
  

Также измените метод делегирования, чтобы передать текущее состояние получено

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

Также обратите внимание, что locationManager.requestWhenInUseAuthorization() не будет работать, если Info.plist не содержит следующих описаний использования, поэтому отредактируйте Info.plist файл и убедитесь, что:

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

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

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

Наконец, вам нужно дождаться вызова обновления местоположения centerViewOnUserLocation , вот так

 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)
}
  

Ответ №4:

Симулятор не показывает текущее местоположение, но вы можете вручную добавить в него местоположение с помощью:

Отладка -> Местоположение -> Пользовательское местоположение, а затем укажите координаты.

Комментарии:

1. я пытался, но я все еще не вижу синюю точку и действительно не работаю

Ответ №5:

В вашем viewDidLoad методе, пожалуйста, напишите приведенный ниже код.
Значение по умолчанию showsUserLocation равно false. , поэтому мы должны обновить его значение по умолчанию.

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

Обратитесь к моему обновленному коду.

Ответ №6:

 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)
    }