获取用户的当前位置/坐标 [英] Get User's Current Location / Coordinates

查看:401
本文介绍了获取用户的当前位置/坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何存储用户的当前位置并在地图上显示位置?

How can I store the user's current location and also show the location on a map?

我可以在地图上显示预定义的坐标,我只是不知道如何从设备接收信息。

I am able to show pre-defined coordinates on a map, I just don't know how to receive information from the device.

另外我知道我必须在Plist中添加一些项目。我该怎么做?

Also I know I have to add some items into a Plist. How can I do that?

推荐答案

要获取用户的当前位置,您需要声明:

To get a user's current location you need to declare:

let locationManager = CLLocationManager()

viewDidLoad()中,您必须实例化 CLLocationManager 类,如下所示:

In viewDidLoad() you have to instanitate the CLLocationManager class, like this:

// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization() 

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

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

然后在CLLocationManagerDelegate方法中,您可以获得用户的当前位置坐标:

Then in CLLocationManagerDelegate method you can get user's current location coordinates:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
    print("locations = \(locValue.latitude) \(locValue.longitude)")
}

在info.plist中,你将必须添加 NSLocationAlwaysUsageDescription
和您的自定义警报消息,如AppName(Demo Ap) p)想要使用您当前的位置。

In the info.plist you will have to add NSLocationAlwaysUsageDescription and your custom alert message like, AppName(Demo App) would like to use your current location.

这篇关于获取用户的当前位置/坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆