如何在swift上的地图视图上显示位置?我相信我的代码是最新的,但模拟器不显示位置或蓝点?

问题描述 投票:2回答:5

我正在尝试使用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()
    }
}
ios swift mapkit core-location
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)
        }
    }
}

多数,现在你能看到你当前的位置和蓝点。


1
投票

要在地图上显示用户位置,请执行以下步骤:

尝试此路径 - 转到产品 - >编辑方案 - >选项 - >选择允许位置模拟并选择默认位置。您还可以使用GPX文件添加自定义位置。设置完成后运行应用程序。

enter image description here


0
投票

模拟器不显示当前位置,但您可以通过以下方式手动添加位置:

调试 - >位置 - >自定义位置然后给出坐标。


0
投票

问题似乎在方法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)
}

0
投票

在您的viewDidLoad方法中,请写下面的代码。 showsUserLocation的默认值是false.所以,我们必须更新它的默认值。

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

请参阅我的更新代码。

© www.soinside.com 2019 - 2024. All rights reserved.