【问题标题】:Show Current Location and Update Location in MKMapView in Swift在 Swift 的 MKMapView 中显示当前位置和更新位置
【发布时间】:2014-10-16 10:51:40
【问题描述】:

我正在学习如何使用新的 Swift 语言(只有 Swift,没有 Objective-C)。为此,我想用地图 (MKMapView) 做一个简单的视图。我想查找并更新用户的位置(例如在 Apple 地图应用中)。

我试过了,但什么也没发生:

import MapKit
import CoreLocation

class MapView : UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var map: MKMapView!
    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        if (CLLocationManager.locationServicesEnabled())
        {
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestAlwaysAuthorization()
            locationManager.startUpdatingLocation()
        }
    }
}

你能帮帮我吗?

【问题讨论】:

标签: ios swift mkmapview cllocationmanager


【解决方案1】:

您必须覆盖CLLocationManager.didUpdateLocations(CLLocationManagerDelegate 的一部分)才能在位置管理器检索当前位置时收到通知:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last{
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        self.map.setRegion(region, animated: true)
    }
}

注意:如果您的目标是 iOS 8 或更高版本,您必须在 Info.plist 中包含 NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription 键才能使定位服务正常工作。

【讨论】:

  • 感谢紫软的回答。但是,要使用该功能,我必须将所有新位置“保存”在一种列表中?那么,startUpdatingLocation() 是否足以更新位置?注意:呃......对不起,但我该怎么做呢? :s 非常感谢!
  • 调用startUpdatingLocation 一次后,每次检测到位置变化时都会触发didUpdateLocations。你可以对这个位置做任何你想做的事情,即将它存储在一个数组中以在地图视图上绘制一条路径。
  • 好的,谢谢。我怎样才能在我的 Info.plist 中包含 NSLocationAlwaysUsageDescription 键?
  • 在 XCode 中,单击 Info.plist 并添加一个新行。使用NSLocationAlwaysUsageDescription 作为键,使用您想要呈现给用户的文本作为值(字符串)。
  • 好的,谢谢!没有价值?
【解决方案2】:

100% 工作、简单的步骤并经过测试

导入库:

import MapKit
import CoreLocation

设置代表:

CLLocationManagerDelegate,MKMapViewDelegate

取变量:

let locationManager = CLLocationManager()

在 viewDidLoad() 上写下这段代码:

self.locationManager.requestAlwaysAuthorization()

    // For use in foreground
    self.locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    }

    mapView.delegate = self
    mapView.mapType = .standard
    mapView.isZoomEnabled = true
    mapView.isScrollEnabled = true

    if let coor = mapView.userLocation.location?.coordinate{
        mapView.setCenter(coor, animated: true)
    }

为位置编写委托方法:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let locValue:CLLocationCoordinate2D = manager.location!.coordinate

    mapView.mapType = MKMapType.standard

    let span = MKCoordinateSpanMake(0.05, 0.05)
    let region = MKCoordinateRegion(center: locValue, span: span)
    mapView.setRegion(region, animated: true)

    let annotation = MKPointAnnotation()
    annotation.coordinate = locValue
    annotation.title = "Javed Multani"
    annotation.subtitle = "current location"
    mapView.addAnnotation(annotation)

    //centerMap(locValue)
}

别忘了在info.plist

中设置权限
<key>NSLocationWhenInUseUsageDescription</key>
<string>This application requires location services to work</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>This application requires location services to work</string>

看起来像:

【讨论】:

    【解决方案3】:

    对于 swift 3 和 XCode 8,我找到了这个答案:

    • 首先,您需要在 info.plist 中设置隐私。插入字符串 NSLocationWhenInUseUsageDescription 以及您想要获取用户位置的说明。例如,设置字符串“For map in application”。

    • 其次,使用这个代码示例

      @IBOutlet weak var mapView: MKMapView!
      
      private var locationManager: CLLocationManager!
      private var currentLocation: CLLocation?
      
      override func viewDidLoad() {
          super.viewDidLoad()
      
          mapView.delegate = self
      
          locationManager = CLLocationManager()
          locationManager.delegate = self
          locationManager.desiredAccuracy = kCLLocationAccuracyBest
      
          // Check for Location Services
      
          if CLLocationManager.locationServicesEnabled() {
              locationManager.requestWhenInUseAuthorization()
              locationManager.startUpdatingLocation()
          }
      }
      
      // MARK - CLLocationManagerDelegate
      
      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 = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000)
                  mapView.setRegion(viewRegion, animated: false)
              }
          }
      }
      
    • 第三,在storyboard中为mapView设置User Location标志。

    【讨论】:

      【解决方案4】:

      MyLocation 是一个 Swift iOS Demo。

      您可以将此演示用于以下用途:

      1. 显示当前位置。

      2. 选择其他位置:在这种情况下停止跟踪该位置。

      3. 在触摸时将图钉添加到 MKMapView(iOS)。

      【讨论】:

      【解决方案5】:

      嗨,有时由于某些奇怪的原因,在代码中设置 showUserLocation 不起作用。

      因此请尝试以下组合。

      在 viewDidLoad() 中

        self.mapView.showsUserLocation = true
      

      在 Xcode 中转到您的故事板,在右侧面板的属性检查器中勾选 用户位置 复选框,如附图中所示。运行您的应用,您应该能够看到用户位置

      【讨论】:

      • 谢谢,复选框“用户位置”正是我要找的——当前位置的蓝点。
      【解决方案6】:

      斯威夫特 5.1

      获取当前位置并在 MKMapView 上设置

      导入库:

      import MapKit
      import CoreLocation
      

      设置代表:

      CLLocationManagerDelegate , MKMapViewDelegate
      

      声明变量:

      let locationManager = CLLocationManager()
      

      在 viewDidLoad() 上写下这段代码:

      self.locationManager.requestAlwaysAuthorization()
      self.locationManager.requestWhenInUseAuthorization()
      
      if CLLocationManager.locationServicesEnabled() {
          locationManager.delegate = self
          locationManager.desiredAccuracy = kCLLocationAccuracyBest
          locationManager.startUpdatingLocation()
      }
      mapView.delegate = self
      mapView.mapType = .standard
      mapView.isZoomEnabled = true
      mapView.isScrollEnabled = true
      
      if let coor = mapView.userLocation.location?.coordinate{
          mapView.setCenter(coor, animated: true)
      }
      

      为位置编写委托方法:

      func locationManager(_ manager: CLLocationManager, didUpdateLocations 
          locations: [CLLocation]) {
          let locValue:CLLocationCoordinate2D = manager.location!.coordinate
      
          mapView.mapType = MKMapType.standard
      
          let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
          let region = MKCoordinateRegion(center: locValue, span: span)
          mapView.setRegion(region, animated: true)
      
          let annotation = MKPointAnnotation()
          annotation.coordinate = locValue
          annotation.title = "You are Here"
          mapView.addAnnotation(annotation)
      }
      

      在 info.plist 中设置权限 *

      <key>NSLocationWhenInUseUsageDescription</key>
      <string>This application requires location services to work</string>
      
      <key>NSLocationAlwaysUsageDescription</key>
      <string>This application requires location services to work</string>
      

      【讨论】:

        【解决方案7】:

        对于 Swift 2,您应该将其更改为以下内容:

        func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            let location = locations.last
        
            let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
            let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        
            self.map.setRegion(region, animated: true)
        }
        

        【讨论】:

          【解决方案8】:

          您只需要设置 MKMapView 的 userTrackingMode。如果您只想显示和跟踪用户位置并实现与 Apple 地图应用程序相同的行为,则没有理由编写额外的代码。

          mapView.userTrackingMode = .follow
          

          https://developer.apple.com/documentation/mapkit/mkmapview/1616208-usertrackingmode 上查看更多信息。

          【讨论】:

            【解决方案9】:

            你必须覆盖CLLocationManager.didUpdateLocations

             func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            
                let userLocation:CLLocation = locations[0] as CLLocation
                locationManager.stopUpdatingLocation()
            
                let location = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
            
                let span = MKCoordinateSpanMake(0.5, 0.5)
            
                let region = MKCoordinateRegion (center:  location,span: span)
            
                mapView.setRegion(region, animated: true)
            }
            

            您还必须将NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription 添加到您的plist 设置Result 作为值

            【讨论】:

              【解决方案10】:

              在 Swift 4 中,我使用了上面定义的 locationManager 委托函数 ..

              func locationManager(manager: CLLocationManager!, 
                  didUpdateLocations locations: [AnyObject]!) {
              

              .. 但这需要改为..

              func locationManager(_ manager: CLLocationManager,
                  didUpdateLocations locations: [CLLocation]) {
              

              这来自 ..https://github.com/lotfyahmed/MyLocation/blob/master/MyLocation/ViewController.swift - 谢谢!

              【讨论】:

                【解决方案11】:
                mapView.showsUserLocation = true
                

                创建 UIButton 并添加此操作

                @IBAction func showCurrentLocation(_ sender: Any) {
                        let coordinate = mapView.userLocation.coordinate
                        let center = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
                        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
                        self.mapView.setRegion(region, animated: true)
                    }
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2013-11-13
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多