iOS 定位 高德地圖

最近項(xiàng)目中有需求需要使用定位即碗,上報(bào)經(jīng)緯度和地址信息,還有可以在地圖界面隨意選擇地點(diǎn),因?yàn)楹秃笈_(tái)經(jīng)緯度匹配的問題断国,所以選擇了高德地圖(百度地圖經(jīng)緯度是有自己算法的)。

1.定位

iOS定位SDK提供后臺(tái)持續(xù)定位的能力榆苞,可持久記錄位置信息稳衬,適用于記軌跡錄。
在調(diào)用定位功能的類中引入

AMapFoundationKit.h 
AMapLocationKit.h

這兩個(gè)頭文件
在調(diào)用定位時(shí)坐漏,需要添加Key薄疚,需要注意的是請(qǐng)?jiān)?SDK 任何類的初始化以及方法調(diào)用之前設(shè)置正確的 Key。
將info.plist的字段改成

NSLocationAlwaysUsageDescription

字段赊琳。
?? ?? 在iOS 11 中街夭,新出現(xiàn)了一個(gè)

NSLocationAlwaysAndWhenInUseUsageDeion

字段,如果以前設(shè)置的NSLocationAlwaysUsageDescription字段無用躏筏,請(qǐng)查看 《iOS11 Xcode9 更新適配》 傳送門
如果需要后臺(tái)持續(xù)定位需要開啟 TARGETS->Capabilities->Background Modes

image.png

開啟定位

self.locationManager = [[AMapLocationManager alloc] init];
[self.locationManager setDelegate:self];
//iOS 9(不包含iOS 9) 之前設(shè)置允許后臺(tái)定位參數(shù)板丽,保持不會(huì)被系統(tǒng)掛起
[self.locationManager setPausesLocationUpdatesAutomatically:NO];
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
// iOS 9(包含iOS 9)之后新特性:將允許出現(xiàn)這種場(chǎng)景,同一app中多個(gè)locationmanager:一些只能在前臺(tái)定位趁尼,另一些可在后臺(tái)定位埃碱,并可隨時(shí)禁止其后臺(tái)定位。
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
    self.locationManager.allowsBackgroundLocationUpdates = NO;
}
// 后臺(tái)定位是否返回逆地理信息
[self.locationManager setLocatingWithReGeocode:YES];
// 開始持續(xù)定位
[self.locationManager startUpdatingLocation];

回調(diào)函數(shù)弱卡,處理經(jīng)緯度及地址信息

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode {
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    if (regeocode) {
      NSLog(@"reGeocode:%@", regeocode);
    }
}

進(jìn)行持續(xù)定位的時(shí)候乃正,有些經(jīng)緯度會(huì)漂移,比如室內(nèi)等信號(hào)不好的地方婶博,可以根據(jù)需求用以下的方法做一些簡(jiǎn)單的處理

// 小于70 認(rèn)為GPS信號(hào)弱
NSString *horizontal = [NSString stringWithFormat:@"GPS信號(hào)為%lf",location.horizontalAccuracy];
// 速度為0 過濾掉
if (location.speed <= 0) {
    self.currLocation = nil;
    NSLog(@"速度為0");
    return;
}
// 計(jì)算距離
MAMapPoint point1 = MAMapPointForCoordinate(CLLocationCoordinate2DMake(self.currLocation.coordinate.latitude,self.currLocation.coordinate.longitude));
MAMapPoint point2 = MAMapPointForCoordinate(CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude));

CLLocationDistance distance = MAMetersBetweenMapPoints(point1,point2);
if (distance > 100) {
    self.currLocation = nil;
    NSLog(@"距離相差過大%f",distance);
    return;
}
// 判斷當(dāng)前經(jīng)緯度與上一個(gè)經(jīng)緯度是否相同,相同則過濾掉
if (self.currLocation == location) {
    self.currLocation = nil;
    NSLog(@"相同經(jīng)緯度");
    return;
} 

2.地圖

初始化地圖

//地圖需要v4.5.0及以上版本才必須要打開此選項(xiàng)(v4.5.0以下版本荧飞,需要手動(dòng)配置info.plist)
[AMapServices sharedServices].enableHTTPS = YES;
///初始化地圖
_mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
_mapView.delegate = self;
[_mapView setZoomLevel:17.5 animated:YES];
[self.view addSubview:_mapView];
// 初始化地理編碼
_search = [[AMapSearchAPI alloc] init];
_search.delegate = self;

點(diǎn)擊地圖上任一點(diǎn)顯示信息凡人,并添加標(biāo)注

#pragma mark 點(diǎn)擊地圖方法
- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate {

if (!self.isCheck) {
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = MAUserTrackingModeNone;
    // 點(diǎn)擊位置的經(jīng)緯度
    _touchMapCoordinate = coordinate;
    // 如果有上一個(gè)標(biāo)注,先刪除
    NSInteger annotationsNum = _mapView.annotations.count;
    if (annotationsNum > 0) {
        for (int i = 0; i < annotationsNum; i ++) {
            NSLog(@"%@",_mapView.annotations);
            if (i < _mapView.annotations.count) {
                id item = [_mapView.annotations objectAtIndex:i];
                [_mapView removeAnnotation:item];
            }
        }
    }
    // 逆地理編碼獲取地址
    [self reocodeSearch];
} else {
    // 逆地理編碼獲取地址
    [self reocodeSearch];
}

}

#pragma mark 逆地理編碼
- (void)reocodeSearch {

AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
regeo.location = [AMapGeoPoint locationWithLatitude:_touchMapCoordinate.latitude longitude:_touchMapCoordinate.longitude];
regeo.requireExtension = YES;
[_search AMapReGoecodeSearch:regeo];

}

#pragma mark 標(biāo)注delegate方法
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
if ([annotation isKindOfClass:[MAUserLocation class]]) {
    return nil;
}

if ([annotation isKindOfClass:[MAPointAnnotation class]])
{
    static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
    CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
    if (annotationView == nil)
    {
        annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
    }
    if (!self.isCheck) {
        annotationView.canShowCallout= YES;       //設(shè)置氣泡可以彈出叹阔,默認(rèn)為NO
        annotationView.animatesDrop = YES;        //設(shè)置標(biāo)注動(dòng)畫顯示挠轴,默認(rèn)為NO
        annotationView.pinColor = MAPinAnnotationColorPurple;
        annotationView.canShowCallout = NO;
        annotationView.enabled = NO;
    } else {
        annotationView.canShowCallout= NO;       //設(shè)置氣泡可以彈出,默認(rèn)為NO
        annotationView.animatesDrop = NO;        //設(shè)置標(biāo)注動(dòng)畫顯示耳幢,默認(rèn)為NO
        annotationView.pinColor = MAPinAnnotationColorPurple;
        annotationView.canShowCallout = NO;
        annotationView.enabled = NO;
    }
    return annotationView;
}
return nil;
}

#pragma mark 逆地理編碼成功
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
if (response.regeocode != nil)
{
    AMapReGeocode *regeocode = response.regeocode;
    // 解析response獲取地址描述岸晦,具體解析見 Demo
    // regeocode.formattedAddress 格式化標(biāo)準(zhǔn)地址
    [self addAnnotationWithAddress:regeocode.formattedAddress];
}
}

#pragma mark 逆地理編碼失敗
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
NSLog(@"Error: %@", error);
}

#pragma mark 添加標(biāo)注并設(shè)置地址內(nèi)容
- (void)addAnnotationWithAddress:(NSString *)address {
MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
pointAnnotation.coordinate = _touchMapCoordinate;
pointAnnotation.title = address;
_touchMapAddress = address;
[_mapView addAnnotation:pointAnnotation];
[_mapView selectAnnotation:pointAnnotation animated:YES];
}

Demo 傳送門
自己學(xué)習(xí)的時(shí)候?qū)懙模瑲g迎大家提出建議和意見

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末睛藻,一起剝皮案震驚了整個(gè)濱河市启上,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌店印,老刑警劉巖冈在,帶你破解...
    沈念sama閱讀 218,941評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異按摘,居然都是意外死亡包券,警方通過查閱死者的電腦和手機(jī)纫谅,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來溅固,“玉大人付秕,你說我怎么就攤上這事∈坦” “怎么了盹牧?”我有些...
    開封第一講書人閱讀 165,345評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)励幼。 經(jīng)常有香客問我汰寓,道長(zhǎng),這世上最難降的妖魔是什么苹粟? 我笑而不...
    開封第一講書人閱讀 58,851評(píng)論 1 295
  • 正文 為了忘掉前任有滑,我火速辦了婚禮,結(jié)果婚禮上嵌削,老公的妹妹穿的比我還像新娘毛好。我一直安慰自己,他們只是感情好苛秕,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評(píng)論 6 392
  • 文/花漫 我一把揭開白布肌访。 她就那樣靜靜地躺著,像睡著了一般艇劫。 火紅的嫁衣襯著肌膚如雪吼驶。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評(píng)論 1 305
  • 那天店煞,我揣著相機(jī)與錄音蟹演,去河邊找鬼。 笑死顷蟀,一個(gè)胖子當(dāng)著我的面吹牛酒请,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播鸣个,決...
    沈念sama閱讀 40,414評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼羞反,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了囤萤?” 一聲冷哼從身側(cè)響起昼窗,我...
    開封第一講書人閱讀 39,319評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎阁将,沒想到半個(gè)月后膏秫,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,775評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年缤削,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了窘哈。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,096評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡亭敢,死狀恐怖滚婉,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情帅刀,我是刑警寧澤让腹,帶...
    沈念sama閱讀 35,789評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站扣溺,受9級(jí)特大地震影響骇窍,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜锥余,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評(píng)論 3 331
  • 文/蒙蒙 一腹纳、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧驱犹,春花似錦嘲恍、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至医舆,卻和暖如春俘侠,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背彬向。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評(píng)論 1 271
  • 我被黑心中介騙來泰國(guó)打工兼贡, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人娃胆。 一個(gè)月前我還...
    沈念sama閱讀 48,308評(píng)論 3 372
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像等曼,于是被迫代替她去往敵國(guó)和親里烦。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容