1.相比iOS8.0之前的地图定位的区别
1.要请求授权
if #available(iOS 8.0, *)
{
templocationManager.requestWhenInUseAuthorization()
}
- 使用这个方法, 一定要注意, 需要在info.plist 文件里面配置对应的key
 - 如果需要在后台获取定位信息,则需要勾选后台模式

虽然说可以在后台获取到位置信息, 但是屏幕上方会出现一个蓝条, 不断提醒用户,解决方法,授权状态发生改变
locationM.requestAlwaysAuthorization()
如果实在iOS9.0之后
需要在iOS8.0的基础上,添加个判断
授权状态发生改变的时候调用


- 设置定位的精确度
 - 设置过滤距离

获取两个经纬度之间的屋里距离
let latitude: CLLocationDegrees = 21.123
let longitude: CLLocationDegrees = 121.123
let loc1: CLLocation = CLLocation(latitude: latitude, longitude: longitude)
let latitude2: CLLocationDegrees = 22.123
let longitude2: CLLocationDegrees = 121.123
let loc2: CLLocation = CLLocation(latitude: latitude2, longitude: longitude2)
let distance = loc1.distanceFromLocation(loc2)
打印当前用户的行走方向,偏离角度以及对应的行走距离,
// locations 位置数组, 是按照时间的升序进行排序, 所以, 如果想要获取最新的位置, 只需要拿到数组的最后一个就好
// coordinate: CLLocationCoordinate2D, 经纬度结构体
// altitude : 海拔
// horizontalAccuracy : 如果这个数字小于0, 就代表位置数据无效
// verticalAccuracy: 垂直精确度, 如果这个值小于0, 就代表海拔数据无效
// course : 航向 , 0 是相对于正北, 0.0--359.9
// speed: 速度
// distanceFromLocation: 计算两个位置之间的物理距离
guard let location = locations.last
else
{
return
}
if location.horizontalAccuracy < 0
{
print("数据无效")
return
}
// 获取当前的方向
// course : 0.0 - 359.9 -> 北偏东, 东偏南
let courseStrArr = ["北偏东", "东偏南", "南偏西", "西偏北"]
let index = Int(location.course) / 90
var courseStr = courseStrArr[index]
// 计算偏离角度
let angle = Int(location.course) % 90
// 判断是否是正方向
if angle == 0
{
let tempStr: NSString! = courseStr
courseStr = tempStr.substringToIndex(1)
}
// 计算移动了多少米
var distance = 0.0
if lastLocation != nil
{
distance = location.distanceFromLocation(lastLocation!)
}
lastLocation = location
// ”北偏东 30度 方向,移动了 8米”
print(courseStr, angle , "方向, 移动了", distance , "米")
地理编码及反地理编码
地理编码
地理编码 : 地址 -> 经纬度
// 懒加载地理编码器
lazy var geoCoder: CLGeocoder = {
return CLGeocoder()
}()
@IBAction func geoCode() {
geoCoder.geocodeAddressString("广州") { (pls: [CLPlacemark]?, error: NSError?) -> Void in
if error == nil{
print("地理编码成功")
}else
{
print("地理编码失败")
}
}
###反地理编码
// 反地理编码 : 经纬度 -> 地址
@IBAction func reverseGeoCode() {
let latitudeStr: NSString! = latitudeTF.text
let longitutudeStr: NSString! = longitudeTF.text
if latitudeStr.length == 0 || longitutudeStr.length == 0
{
return
}
let latitude: Double! = CLLocationDegrees(latitudeTF.text!)
let longitude: Double! = CLLocationDegrees(longitudeTF.text!)
let location = CLLocation(latitude: latitude, longitude: longitude)
geoCoder.reverseGeocodeLocation(location) { (pls: [CLPlacemark]?, error: NSError?) -> Void in
if error == nil{
print("反地理编码成功")
}else
{
print("反地理编码失败")
}
}
```
希望你我一起共同努力学习


虽然说可以在后台获取到位置信息, 但是屏幕上方会出现一个蓝条, 不断提醒用户,解决方法,授权状态发生改变




浙公网安备 33010602011771号