CLLocation(位置)
- CLLocation用來表示某個(gè)位置的地理信息,比如經(jīng)緯度、海拔等等
CLLocation常用屬性
- 當(dāng)前位置所在的經(jīng)緯度數(shù)據(jù)
@property(readonly, nonatomic) CLLocationCoordinate2D coordinate;
@property(readonly, nonatomic) CLLocationDistance altitude;
- 路線,航向(取值范圍是0.0° ~ 359.9°,0.0°代表正北方向),負(fù)數(shù)代表航向不可用
@property(readonly, nonatomic) CLLocationDirection course;
@property(readonly, nonatomic) CLLocationSpeed speed;
CLLocation(位置)常用方法
- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location
3. 場景演練
1. 場景演示:打印當(dāng)前用戶的行走方向,偏離角度以及對(duì)應(yīng)的行走距離,
例如:”北偏東30度方向,移動(dòng)了8米”
2. 實(shí)現(xiàn)步驟:
1> 獲取對(duì)應(yīng)的方向偏向(例如”正東”,”東偏南”)
2> 獲取對(duì)應(yīng)的偏離角度(并判斷是否是正方向)
3> 計(jì)算行走距離
4> 打印信息
// 1.取出位置,建議取出最后一個(gè),因?yàn)樽詈笠粋€(gè)最準(zhǔn)確
guard let location = locations.last else {return}
// 2.判斷位置是否可用
if location.horizontalAccuracy < 0 {return}
// 3.判斷航向是否可用
if location.course < 0 {return}
// 場景演示:打印當(dāng)前用戶的行走方向,偏離角度以及對(duì)應(yīng)的行走距離,
// 例如:”北偏東 30度方向,移動(dòng)了8米”
// 確定方向
let angleStrs = ["北偏東", "東偏南", "南偏西", "西偏北"];
let index = Int(location.course / 90)
var angleStr = angleStrs[index]
// 確定偏移角度
let angle = location.course % 90
if Int(angle) == 0 {
// swift
// let index = angleStr.startIndex.advancedBy(1)
// angleStr = "正" + angleStr.substringToIndex(index)
// OC
angleStr = "正" + (angleStr as NSString).substringToIndex(1)
}
// 計(jì)算移動(dòng)了多少米
let lastLoc = lastLocation ?? location
let distance = location.distanceFromLocation(lastLoc)
lastLocation = location
// 拼接字符串,并打印
if Int(angle) == 0 {
print("\(angleStr), 移動(dòng)了\(distance)米")
} else {
print("\(angleStr) \(angle)角度, 移動(dòng)了\(distance)米")
}
4. 注意事項(xiàng)
- 使用位置前, 務(wù)必判斷當(dāng)前獲取的位置是否有效
- 如果水平精確度小于零, 代表雖然可以獲取位置對(duì)象, 但是數(shù)據(jù)錯(cuò)誤, 不可用
if (location.horizontalAccuracy < 0) return;
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。