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

Posted

技术标签:

【中文标题】如何在swift的地图视图上显示位置?我相信我的代码是最新的,但模拟器没有显示位置或蓝点?【英文标题】: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? 【发布时间】:2019-04-24 05:54:21 【问题描述】:

我正在尝试使用 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()
    

【问题讨论】:

从菜单中选择调试 -> 位置 -> 自定义位置,然后输入您的坐标 在 setupLocationManager 方法中添加 locationManager.requestWhenInUseAuthorization() 首先为您的地图设置 self.mapView.showsUserLocation = true 并在启动应用程序后调试 -> 位置 -> 输入自定义位置或从列表中选择一个 我在添加后收到此错误消息 [11334:14070810] 致命错误:在隐式展开可选值时意外发现 nil 添加异常断点并检查它在哪里崩溃 【参考方案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 文件添加自定义位置。 设置干净后运行应用程序。

【讨论】:

不幸的是仍然没有蓝点或我的位置【参考方案3】:

问题似乎出在方法checkLocationAuthorrization,这里你必须在状态为notDetermined时询问locationManager.requestWhenInUseAuthorization(),像这样:

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】:

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

Debug -> Location -> Custom Location 然后给出坐标。

【讨论】:

我试过了,但我还是看不到蓝点,真的不工作【参考方案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)
    

【讨论】:

以上是关于如何在swift的地图视图上显示位置?我相信我的代码是最新的,但模拟器没有显示位置或蓝点?的主要内容,如果未能解决你的问题,请参考以下文章

swift - 如何在应用程序运行时顺利加载谷歌地图视图

Swift:如何在地图视图上启用和禁用注释?

延迟显示 UIMapView 直到地图在 Swift 中完全加载

如何在我的应用程序视图中显示地图?

如何在谷歌地图上快速更改我的位置按钮的位置

如何在没有 Storyboard 的情况下推送新视图 Swift