在Swift中的MKMapView中显示当前位置和更新位置

PMI*_*MIW 44 mkmapview cllocationmanager ios swift

我正在学习如何使用新的Swift语言(只有Swift,没有Objective-C).要做到这一点,我想用map(MKMapView)做一个简单的视图.我想查找并更新用户的位置(例如在Apple Map应用程序中).

我试过了,但没有发生任何事:

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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请你帮助我好吗?

zis*_*oft 65

您必须覆盖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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • NSLocationWhenInUseUsageDescription也应该有效,不是吗? (2认同)

Mr.*_*ani 26

100%工作,简单的步骤和测试

导入库:

import MapKit
import CoreLocation
Run Code Online (Sandbox Code Playgroud)

设置代表:

CLLocationManagerDelegate,MKMapViewDelegate
Run Code Online (Sandbox Code Playgroud)

变量:

let locationManager = CLLocationManager()
Run Code Online (Sandbox Code Playgroud)

在viewDidLoad()上编写此代码:

self.locationManager.requestAlwaysAuthorization()

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)
    }
Run Code Online (Sandbox Code Playgroud)

写位置的委托方法:

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)
}
Run Code Online (Sandbox Code Playgroud)

不要忘记在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>
Run Code Online (Sandbox Code Playgroud)

它看起来像:

在此输入图像描述


Evg*_*rev 20

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

  • 首先,您需要将隐私设置为info.plist.插入字符串NSLocationWhenInUseUsageDescription以及您想要获取用户位置的描述.例如,设置字符串"For application 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)
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 第三,在storyView的storyboard中设置User Location标志.


Ahm*_*tfy 7

MyLocation 是一个Swift iOS演示.

您可以将此演示用于以下内容:

  1. 显示当前位置.

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

  3. 触摸时将推针添加到MKMapView(iOS).

  • 请不要在多个问题上添加相同的答案.回答最好的一个并将其余部分标记为重复.请参阅[在几个问题中添加重复答案是否可以接受?](http://meta.stackexchange.com/q/104227) (3认同)

Vis*_*ela 5

您好有时在代码中设置showsUserLocation 会因为一些奇怪的原因而不起作用。

因此,请尝试以下组合。

在 viewDidLoad()

  self.mapView.showsUserLocation = true
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明


小智 5

斯威夫特 5.1

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

导入库:

import MapKit
import CoreLocation
Run Code Online (Sandbox Code Playgroud)

设置代表:

CLLocationManagerDelegate , MKMapViewDelegate
Run Code Online (Sandbox Code Playgroud)

声明变量:

let locationManager = CLLocationManager()
Run Code Online (Sandbox Code Playgroud)

在 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)
}
Run Code Online (Sandbox Code Playgroud)

编写位置委托方法:

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)
}
Run Code Online (Sandbox Code Playgroud)

在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>
Run Code Online (Sandbox Code Playgroud)