最近項(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迎大家提出建議和意見