IOS入门笔记之地理位置定位系统

2020-01-14 19:05:00王冬梅

•地图应用需要掌握的:

•框架:MapKit

•操作类:MKMapView

2、定位服务

•属性: 

•desiredAccuracy设置定位精确度,这是一个常量属性,一般用best
•distanceFilter 重新定位的最小变化距离

方法:

•设置什么时候开启定位的状态 •requestAlwaysAuthorization() 始终开启定位
•requestWhenInUseAuthorization() 当app进入前台的时候开启定位(iOS8的新方法)
•类方法locationServicesEnabled() 是否有定位服务功能(CLLocationManager)
•startUpdatingLocation() 开启定位

代理:

•代理的协议:
•代理的方法:可以直接进入这个库的API查看,只要就是定位错误调用的代理方法,定位成功调用的代理方法等等;

涉及到的对象

•locations: CLLocation 该CLLocation对象的属性: •coordinate •longitude/latitude

英语词汇积累:

•accuracy 英 'ækjʊrəsɪ n. [数] 精确度,准确性
•filter 英 'fɪltə 滤波器 过滤器;筛选;滤光器 过滤;渗透;用过滤法除去

下面提供的是Swift源码:


//
// ViewController.swift
// LocationManager
//
// Created by HEYANG on //.
// Copyright © 年 HEYANG. All rights reserved.
//
import UIKit
// 需要导入CoreLocation框架
import CoreLocation
class ViewController: UIViewController,CLLocationManagerDelegate {
// 声明一个全局变量
var locationManager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
// 设置定位的精确度
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// 设置定位变化的最小距离 距离过滤器
locationManager.distanceFilter = 
// 设置请求定位的状态
if #available(iOS ., *) {
locationManager.requestWhenInUseAuthorization()
} else {
// Fallback on earlier versions
print("hello")
}//这个是在ios之后才有的
// 设置代理为当前对象
locationManager.delegate = self;
if CLLocationManager.locationServicesEnabled(){
// 开启定位服务
locationManager.startUpdatingLocation()
}else{
print("没有定位服务")
}
}
// 定位失败调用的代理方法
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print(error)
}
// 定位更新地理信息调用的代理方法
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count > 
{
let locationInfo = locations.last!
let alert:UIAlertView = UIAlertView(title: "获取的地理坐标",
message: "经度是:(locationInfo.coordinate.longitude),维度是:(locationInfo.coordinate.latitude)",
delegate: nil, cancelButtonTitle: "是的")
alert.show()
}
}
}