Swift - 使用CoreLocation实现定位(经纬度、海拔、速度、距离等)

(1)在 info.plist里加入定位描述(Value值为空也可以):
NSLocationWhenInUseDescription :允许在前台获取GPS的描述
NSLocationAlwaysUsageDescription :允许在后台获取GPS的描述
(2)代码如下:

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    //定位管理器
    let locationManager:CLLocationManager = CLLocationManager()

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!
    @IBOutlet weak var label4: UILabel!
    @IBOutlet weak var label5: UILabel!
    @IBOutlet weak var label6: UILabel!
    @IBOutlet weak var label7: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        //设置定位服务管理器代理
        locationManager.delegate = self
        //设置定位进度
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        //更新距离
        locationManager.distanceFilter = 100
        发送授权申请
        locationManager.requestAlwaysAuthorization()
        if (CLLocationManager.locationServicesEnabled())
        {
            //允许使用定位服务的话,开启定位服务更新
            locationManager.startUpdatingLocation()
            print("定位开始")
        }
    }

    //定位改变执行,可以得到新位置、旧位置
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //获取最新的坐标
        let currLocation:CLLocation = locations.last!
        label1.text = "经度:\(currLocation.coordinate.longitude)"
        //获取纬度
        label2.text = "纬度:\(currLocation.coordinate.latitude)"
        //获取海拔
        label3.text = "海拔:\(currLocation.altitude)"
        //获取水平精度
        label4.text = "水平精度:\(currLocation.horizontalAccuracy)"
        //获取垂直精度
        label5.text = "垂直精度:\(currLocation.verticalAccuracy)"
        //获取方向
        label6.text = "方向:\(currLocation.course)"
        //获取速度
        label7.text = "速度:\(currLocation.speed)"
    }
}

转自:http://www.hangge.com/blog/cache/detail_783.html#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值