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

问题描述 投票:39回答:7

我正在学习如何使用新的Swift语言(只有Swift,没有Objective-C)。要做到这一点,我想用地图(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()
        }
    }
}

请你帮助我好吗?

ios swift mkmapview cllocationmanager
7个回答
60
投票

您必须覆盖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密钥才能使位置服务正常工作。


21
投票

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>

它看起来像:

enter image description here


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) } } }
  • 第三,在storyView的storyboard中设置User Location标志。

7
投票

MyLocation是Swift iOS演示。

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

  1. 显示当前位置。
  2. 选择其他位置:在这种情况下,请停止跟踪位置。
  3. 触摸时将推针添加到MKMapView(iOS)。

3
投票

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

1
投票

你必须覆盖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作为值


1
投票

在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 - 谢谢!

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