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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25449469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:00:44  来源:igfitidea点击:

Show Current Location and Update Location in MKMapView in Swift

iosswiftmkmapviewcllocationmanager

提问by PMIW

I am learning how to use the new Swift language (only Swift, no Objective-C). To do it, I want to do a simple view with a map (MKMapView). I want to find and update the location of the user (like in the Apple Map app).

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

I tried this, but nothing happened:

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

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

Could you please help me?

请你帮助我好吗?

回答by zisoft

You have to override CLLocationManager.didUpdateLocations(part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:

您必须覆盖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)
    }
}

NOTE: If your target is iOS 8 or above, you must include the NSLocationAlwaysUsageDescriptionor NSLocationWhenInUseUsageDescriptionkey in your Info.plist to get the location services to work.

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

回答by Mr.Javed Multani

100% working, easy steps and tested

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

Import libraries:

导入库:

import MapKit
import CoreLocation

set delegates:

设置代表:

CLLocationManagerDelegate,MKMapViewDelegate

Take variable:

取变量:

let locationManager = CLLocationManager()

write this code on viewDidLoad():

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

Write delegate method for location:

为位置编写委托方法:

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

Do not forgot to set permission in info.plist

不要忘记在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>

It's look like:

它看起来像:

enter image description here

在此处输入图片说明

回答by Evgeny Karev

For swift 3 and XCode 8 I find this answer:

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

  • First, you need set privacy into info.plist. Insert string NSLocationWhenInUseUsageDescriptionwith your description why you want get user location. For example, set string "For map in application".

  • Second, use this code example

    @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)
            }
        }
    }
    
  • Third, set User Location flag in storyboard for mapView.

  • 首先,您需要在 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)
            }
        }
    }
    
  • 第三,在故事板中为 mapView 设置用户位置标志。

回答by Ahmed Lotfy

MyLocationis a Swift iOS Demo.

MyLocation是一个 Swift iOS 演示。

You can use this demo for the following:

您可以将此演示用于以下目的:

  1. Show the current location.

  2. Choose other location: in this case stop tracking the location.

  3. Add a push pin to a MKMapView(iOS) when touching.

  1. 显示当前位置。

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

  3. 触摸时向 MKMapView(iOS) 添加图钉。

回答by Mark

For Swift 2, you should change it to the following:

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

回答by Vision Mkhabela

Hi Sometimes setting the showsUserLocation in code doesn't work for some weird reason.

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

So try a combination of the following.

因此,请尝试以下组合。

In viewDidLoad()

在 viewDidLoad()

  self.mapView.showsUserLocation = true

Go to your storyboard in Xcode, on the right panel's attribute inspector tick the User locationcheck box, like in the attached image. run your app and you should be able to see the User location

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

enter image description here

在此处输入图片说明

回答by Tybion

In Swift 4, I had used the locationManager delegate function as defined above ..

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

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

.. but this needed to be changed to ..

.. 但这需要改为..

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

This came from .. https://github.com/lotfyahmed/MyLocation/blob/master/MyLocation/ViewController.swift- thanks!

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

回答by MiladiuM

you have to override CLLocationManager.didUpdateLocations

你必须覆盖 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)
}

you also have to add NSLocationWhenInUseUsageDescriptionand NSLocationAlwaysUsageDescriptionto your plist setting Resultas value

您还必须将NSLocationWhenInUseUsageDescription和添加NSLocationAlwaysUsageDescription到您的 plist 设置中Result作为值

回答by Raksha.

Swift 5.1

斯威夫特 5.1

Get Current Location and Set on MKMapView

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

Import libraries:

导入库:

import MapKit
import CoreLocation

set delegates:

设置代表:

CLLocationManagerDelegate , MKMapViewDelegate

Declare variable:

声明变量:

let locationManager = CLLocationManager()

Write this code on viewDidLoad():

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

Write delegate method for location:

为位置编写委托方法:

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

Set permission in info.plist *

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

回答by Vincent Friedrich

You just need to set the userTrackingMode of the MKMapView. If you only want to display and track the user location and implement the same behaviour as the Apple Maps app uses, there is no reason for writing additional code.

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

mapView.userTrackingMode = .follow

See more at https://developer.apple.com/documentation/mapkit/mkmapview/1616208-usertrackingmode.

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