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

时间:2019-04-24 05:54:22

标签: 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()
    }
}

6 个答案:

答案 0 :(得分: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 :(得分:1)

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

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

enter image description here

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

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

请参阅我的更新代码。

答案 4 :(得分: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)
}

答案 5 :(得分:0)

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