一、蘋果地圖相關(guān)
第一、室外定位
**一.新建工程,在工程 Build Phases 中的 Link Binary With Libraries 中添加框架**
CoreLocation.framework
MapKit.framework
**二.建議創(chuàng)建 PCH 文件,在文件中導(dǎo)入頭文件**
#import <MapKit>
#import <CoreLocation>
**三.在相關(guān)控制器中遵守協(xié)議**
<CLLocationManagerDelegate>
<MKMapViewDelegate>
**四.申明相關(guān)屬性**
@property (nonatomic, retain)MKMapView *mapView;
@property (nonatomic, retain)CLLocationManager *locaManager;
**五.在 ViewDidLoad 方法或者其他相關(guān)方法里實現(xiàn)以下代碼**
//定位管理器
self.locaManager = [[CLLocationManager alloc]init];
//如果沒有授權(quán)則請求用戶授權(quán)
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
[self.locaManager requestWhenInUseAuthorization];
}else if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse){
//設(shè)置代理
self.locaManager.delegate = self;
//設(shè)置定位精度
self.locaManager.desiredAccuracy = kCLLocationAccuracyBest;
//定位頻率,每隔多少米定位一次
CLLocationDistance distance = 10.0;//十米定位一次
self.locaManager.distanceFilter = distance;
//啟動跟蹤定位
[self.locaManager startUpdatingLocation];
}
//初始化地圖視圖
self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(10, 80, WIDTH-20, 160)];
//設(shè)置地圖樣式為基本樣式(這里有三種樣式)
self.mapView.mapType = MKMapTypeStandard;
//是否顯示當(dāng)前位置
self.mapView.showsUserLocation = YES;
//設(shè)置代理
self.mapView.delegate = self;
[self.view addSubview:self.mapView];
**六.實現(xiàn)相關(guān)代理方法**
//獲取用戶位置
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
//點擊大頭針,出現(xiàn)信息
userLocation.title = @"我的位置";
//讓地圖視圖轉(zhuǎn)移到用戶當(dāng)前位置
[mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
//設(shè)置精度,以及顯示用戶所在地
MKCoordinateSpan span = MKCoordinateSpanMake(1, 1);//比例尺為1:10^5,1厘米代表1公里
MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate, span);
[mapView setRegion:region animated:YES];
}
//獲取經(jīng)緯度
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
CLLocation *currLocation = [locations lastObject];
NSLog(@"后臺定位的經(jīng)度%f 緯度%f 海拔%f 行進方向%f",currLocation.coordinate.longitude,currLocation.coordinate.latitude,currLocation.altitude,currLocation.course);
[self.model bianlinowlat:currLocation.coordinate.latitude nowlong:currLocation.coordinate.longitude];
}
//計算移動距離 (根據(jù)經(jīng)緯度)
-(float)julinowlat:(double)nowlat nowlong:(double)nowlong oldWeiZhi:(NSDictionary *)dict
{
CLLocation *orig=[[CLLocation alloc] initWithLatitude:[dict[@"weidu"] doubleValue] longitude:[dict[@"jingdu"] doubleValue]];
CLLocation* dist=[[CLLocation alloc] initWithLatitude:nowlat longitude:nowlong];
CLLocationDistance kilometers=[orig distanceFromLocation:dist];
return kilometers;
}
**七.配置 info.list 文件**
增加屬性 NSLocationWhenInUseUsageDescription
第二、定位城市

圖片.png
1.引入文件
#import <CoreLocation>
#import "TQLocationConverter.h"
#import "ZCChinaLocation.h"
2.導(dǎo)入?yún)f(xié)議代理和定義屬性
<CLLocationManagerDelegate>
/// 定位
@property (nonatomic , strong) CLLocationManager *locationManager;
/// 得到當(dāng)前位置的經(jīng)緯度
@property (nonatomic , assign) CLLocationCoordinate2D curCoordinate2D;
3.viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
// 背景顏色
// self.view.backgroundColor = NavColor;
self.view.backgroundColor = [UIColor orangeColor];
[self locationInit];
// 導(dǎo)航欄
[self createNavView];
// 中部視圖
[self createCenterView];
}
4.定位初始化
/// 定位初始化
- (void)locationInit{
NSLog(@"定位初始化");
//定位管理器
self.locationManager=[[CLLocationManager alloc]init];
//如果沒有授權(quán)則請求用戶授權(quán)
if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined ){
[_locationManager requestWhenInUseAuthorization];
}else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedAlways || [CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
//設(shè)置代理
_locationManager.delegate=self;
//設(shè)置定位精度
// [self.locationManager setAllowsBackgroundLocationUpdates:YES];
_locationManager.desiredAccuracy=kCLLocationAccuracyBest;
_locationManager.pausesLocationUpdatesAutomatically = NO;
//定位頻率,每隔多少米定位一次
CLLocationDistance distance = 10;
_locationManager.distanceFilter=distance;
//啟動跟蹤定位
[_locationManager startUpdatingLocation];
}
}
5.代理方法及地理經(jīng)緯度轉(zhuǎn)換
#pragma mark - 代理方法相關(guān)
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation> *)locations{
CLLocation *currentLoction = [locations lastObject];
/// 得到當(dāng)前位置的經(jīng)緯度
self.curCoordinate2D = currentLoction.coordinate;
NSLog(@"定位直接得到的坐標(biāo)===%f %f",_curCoordinate2D.latitude,_curCoordinate2D.longitude);
[self.locationManager stopUpdatingLocation];
/// 判斷當(dāng)前坐標(biāo)是否在中國
BOOL isChina = [[ZCChinaLocation shared] isInsideChina:(CLLocationCoordinate2D){_curCoordinate2D.latitude,_curCoordinate2D.longitude}];
if (isChina) {
/// 轉(zhuǎn)換坐標(biāo) 不轉(zhuǎn)換會出現(xiàn)偏移
_curCoordinate2D = [TQLocationConverter transformFromWGSToGCJ:_curCoordinate2D];
//獲得地理位置名字
[self googleMapAddress];
}
}
6.地理經(jīng)緯度轉(zhuǎn)換后獲取相關(guān)位置
// 獲得地理位置名字
- (NSString *)googleMapAddress{
__block NSString *addressStr;
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
CLLocation *location = [[CLLocation alloc] initWithLatitude:_curCoordinate2D.latitude longitude:_curCoordinate2D.longitude];
NSLog(@"轉(zhuǎn)換后得到的坐標(biāo)===%f %f",_curCoordinate2D.latitude,_curCoordinate2D.longitude);
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark> * _Nullable placemarks, NSError * _Nullable error) {
if (error || placemarks.count == 0) {
addressStr = @"";
NSLog(@"獲取定理位置失敗");
}else{
addressStr = [placemarks firstObject].locality;
NSLog(@"------------ %@",addressStr);
NSString *city = [addressStr substringWithRange:NSMakeRange(0, 2) ];
[_navView.LocationBtn setTitle:city forState:UIControlStateNormal];
//存儲city 用以判斷下次app進入city默認(rèn)顯示值
[[NSUserDefaults standardUserDefaults] setObject:city forKey:@"city"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}];
return addressStr;
}
7.點擊城市按鈕 (單次點擊和多次點擊,開了定位權(quán)限點擊和關(guān)了定位權(quán)限點擊)
- (void)locationBtnClick:(UIButton *)sender{
[MSUPermissionTool getLocationPermission:NO result:^(NSInteger authStatus) {
if (authStatus == 1 || authStatus == 0) {
self.hidesBottomBarWhenPushed = YES;
MSULocationController *location = [[MSULocationController alloc] init];
[self presentViewController:location animated:YES completion:nil];
self.hidesBottomBarWhenPushed = NO;
}else{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"溫馨提示" message:@"請去-> [設(shè)置 - 隱私 - 定位服務(wù) - 秀貝] 打開訪問開關(guān)" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//確定按鈕點擊事件處理
}]];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
二、百度地圖(地圖視圖加搜索附近功能,簡易版,未加任何性能優(yōu)化)

圖片.png
問題:打開百度地圖后,發(fā)現(xiàn)百度地圖顯示錯誤,控制臺輸出提示引擎初始化失?。淮藛栴}還會導(dǎo)致第二次登錄進入百度地圖控制器界面報錯,報錯位置在 self.mapView =[[BMKMapView alloc] init];
解決方案:
第一步:

CEAE347C-00F4-4E94-8E3C-55CEB5E5E49E.png

66C43601-F894-428C-B402-B31F979CA04F.png
第二步:
卸載真機上的app 重新運行!
0、在百度開放平臺注冊,導(dǎo)入相關(guān)依賴庫

D2F17BED-9BA5-43ED-AE14-567E2DE15C1B.png
1、cocoapods 集成百度地圖框架 pod "BaiduMapKit"
2、導(dǎo)入相關(guān)頭文件
#import <BaiduMapKit/BaiduMapAPI_Map/BMKMapView.h> //mapview 顯示相關(guān)
#import <BaiduMapKit/BaiduMapAPI_Location/BMKLocationService.h> //定位相關(guān)
#import <BaiduMapAPI_Search/BMKGeocodeSearch.h> //geo編碼和反geo編碼相關(guān)
#import <BaiduMapAPI_Search/BMKPoiSearchType.h> //定位信息相關(guān)
@property (nonatomic , strong) BMKMapView* mapView;
@property (nonatomic , strong) BMKLocationService *localService;
@property(nonatomic,strong)BMKGeoCodeSearch* geocodesearch;
@property(nonatomic,assign)NSInteger currentSelectLocationIndex;
@property(nonatomic,assign)CLLocationCoordinate2D currentCoordinate;
@property (nonatomic , strong) UITableView *tableView;
@property (nonatomic , strong) NSMutableArray *dataArr;
3、viewDidLoad初始化
// mapview 初始化相關(guān)
self.mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 300)];
[self.view addSubview:_mapView];
_mapView.zoomEnabled=NO;
_mapView.zoomEnabledWithTap=NO;
_mapView.zoomLevel=17;
_mapView.showsUserLocation = NO;// 先關(guān)閉顯示的定位圖層
_mapView.userTrackingMode = BMKUserTrackingModeFollow;//設(shè)置定位的狀態(tài)
self.mapView.showsUserLocation = YES;//顯示定位圖層
self.currentSelectLocationIndex = 0;
// 隱藏百度地圖logo
UIView *mView = _mapView.subviews.firstObject;
for (id logoView in mView.subviews)
{
if ([logoView isKindOfClass:[UIImageView class]])
{
UIImageView *b_logo = (UIImageView*)logoView;
b_logo.hidden = YES;
}
}
// 定位初始化
self.localService = [[BMKLocationService alloc] init];
_localService.delegate = self;
[_localService startUserLocationService];
//geo編碼相關(guān)
self.geocodesearch = [[BMKGeoCodeSearch alloc] init];
_geocodesearch.delegate = self;
//初始化tableview列表
self.dataArr = [NSMutableArray array];
[self createMyTableView];
4、內(nèi)存優(yōu)化相關(guān)
-(void)viewWillAppear:(BOOL)animated
{
[_mapView viewWillAppear];
_mapView.delegate = self; // 此處記得不用的時候需要置nil,否則影響內(nèi)存的釋放
self.localService.delegate = self;
self.geocodesearch.delegate = self;
}
-(void)viewWillDisappear:(BOOL)animated
{
[_mapView viewWillDisappear];
_mapView.delegate = nil; // 不用時,置nil
self.localService.delegate = nil;
self.geocodesearch.delegate = nil;
}
- (void)dealloc
{
if (_mapView)
{
_mapView = nil;
}
if (_geocodesearch)
{
_geocodesearch = nil;
}
if (_localService)
{
_localService = nil;
}
}
5、tableview 相關(guān)
#pragma mark - tableview
- (void)createMyTableView{
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 300, WIDTH, HEIGHT-300) style:UITableViewStylePlain];
_tableView.backgroundColor = [UIColor yellowColor];
_tableView.dataSource = self;
_tableView.delegate = self;
[self.view addSubview:_tableView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellID = @"haha";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
}
BMKPoiInfo *model=[self.dataArr objectAtIndex:indexPath.row];
cell.textLabel.text=model.name;
cell.detailTextLabel.text=model.address;
cell.detailTextLabel.textColor=[UIColor grayColor];
if (self.currentSelectLocationIndex==indexPath.row){
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}
else{
cell.accessoryType=UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}
6、currentCoordinate的set方法,用于反geo檢索
- (void)setCurrentCoordinate:(CLLocationCoordinate2D)currentCoordinate{
_currentCoordinate=currentCoordinate;
BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
reverseGeocodeSearchOption.reverseGeoPoint = currentCoordinate;
BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
if(flag)
{
NSLog(@"反geo檢索發(fā)送成功");
}
else
{
NSLog(@"反geo檢索發(fā)送失敗");
}
}
7、#pragma mark - 地圖代理相關(guān)
/**
*在地圖View將要啟動定位時,會調(diào)用此函數(shù)
*/
- (void)willStartLocatingUser
{
NSLog(@"start locate");
}
/**
*用戶方向更新后,會調(diào)用此函數(shù)
*@param userLocation 新的用戶位置
*/
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
[self.mapView updateLocationData:userLocation];
// NSLog(@"heading is %@",userLocation.heading);
}
/**
*用戶位置更新后,會調(diào)用此函數(shù)
*@param userLocation 新的用戶位置
*/
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
isFirstLocation=NO;
[self.mapView updateLocationData:userLocation];
self.currentCoordinate = userLocation.location.coordinate;
NSLog(@"地理位置信息 %f %f",self.currentCoordinate.latitude,self.currentCoordinate.longitude);
if (self.currentCoordinate.latitude!=0)
{
[self.localService stopUserLocationService];
}
}
/**
*在地圖View停止定位后,會調(diào)用此函數(shù)
*/
- (void)didStopLocatingUser
{
NSLog(@"stop locate");
}
/**
*定位失敗后,會調(diào)用此函數(shù)
*@param error 錯誤號,參考CLError.h中定義的錯誤號
*/
- (void)didFailToLocateUserWithError:(NSError *)error
{
NSLog(@"location error");
}
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate
{
NSLog(@"map view: click blank");
}
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
if (!isFirstLocation)
{
// CLLocationCoordinate2D tt =[mapView convertPoint:self.centerCallOutImageView.center toCoordinateFromView:self.centerCallOutImageView];
// self.currentCoordinate=tt;
}
}
8.geo檢索代理
#pragma mark - BMKGeoCodeSearchDelegate
/**
*返回地址信息搜索結(jié)果
*@param searcher 搜索對象
*@param result 搜索結(jié)BMKGeoCodeSearch果
*@param error 錯誤號,@see BMKSearchErrorCode
*/
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
NSLog(@"返回地址信息搜索結(jié)果,失敗-------------");
}
/**
*返回反地理編碼搜索結(jié)果
*@param searcher 搜索對象
*@param result 搜索結(jié)果
*@param error 錯誤號,@see BMKSearchErrorCode
*/
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
if (error == BMK_SEARCH_NO_ERROR)
{
[self.dataArr removeAllObjects];
[self.dataArr addObjectsFromArray:result.poiList];
if (isFirstLocation)
{
//把當(dāng)前定位信息自定義組裝 放進數(shù)組首位
BMKPoiInfo *first =[[BMKPoiInfo alloc]init];
first.address=result.address;
first.name=@"[當(dāng)前位置]";
first.pt=result.location;
first.city=result.addressDetail.city;
[self.dataArr insertObject:first atIndex:0];
}
[self.tableView reloadData];
}
}