一、苹果地图相关
第一、室外定位
**一.新建工程,在工程 Build Phases 中的 Link Binary With Libraries 中添加框架**
CoreLocation.framework
MapKit.framework
**二.建议创建 PCH 文件,在文件中导入头文件**
#import <MapKit>
#import <CoreLocation>
**三.在相关控制器中遵守协议**
<CLLocationManagerDelegate>
<MKMapViewDelegate>
**四.申明相关属性**
@property (nonatomic, retain)MKMapView *mapView;
@property (nonatomic, retain)CLLocationManager *locaManager;
**五.在 ViewDidLoad 方法或者其他相关方法里实现以下代码**
//定位管理器
self.locaManager = [[CLLocationManager alloc]init];
//如果没有授权则请求用户授权
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
[self.locaManager requestWhenInUseAuthorization];
}else if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse){
//设置代理
self.locaManager.delegate = self;
//设置定位精度
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)];
//设置地图样式为基本样式(这里有三种样式)
self.mapView.mapType = MKMapTypeStandard;
//是否显示当前位置
self.mapView.showsUserLocation = YES;
//设置代理
self.mapView.delegate = self;
[self.view addSubview:self.mapView];
**六.实现相关代理方法**
//获取用户位置
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
//点击大头针,出现信息
userLocation.title = @"我的位置";
//让地图视图转移到用户当前位置
[mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
//设置精度,以及显示用户所在地
MKCoordinateSpan span = MKCoordinateSpanMake(1, 1);//比例尺为1:10^5,1厘米代表1公里
MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate, span);
[mapView setRegion:region animated:YES];
}
//获取经纬度
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
CLLocation *currLocation = [locations lastObject];
NSLog(@"后台定位的经度%f 纬度%f 海拔%f 行进方向%f",currLocation.coordinate.longitude,currLocation.coordinate.latitude,currLocation.altitude,currLocation.course);
[self.model bianlinowlat:currLocation.coordinate.latitude nowlong:currLocation.coordinate.longitude];
}
//计算移动距离 (根据经纬度)
-(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
第二、定位城市
1.引入文件
#import <CoreLocation>
#import "TQLocationConverter.h"
#import "ZCChinaLocation.h"
2.导入协议代理和定义属性
<CLLocationManagerDelegate>
/// 定位
@property (nonatomic , strong) CLLocationManager *locationManager;
/// 得到当前位置的经纬度
@property (nonatomic , assign) CLLocationCoordinate2D curCoordinate2D;
3.viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
// 背景颜色
// self.view.backgroundColor = NavColor;
self.view.backgroundColor = [UIColor orangeColor];
[self locationInit];
// 导航栏
[self createNavView];
// 中部视图
[self createCenterView];
}
4.定位初始化
/// 定位初始化
- (void)locationInit{
NSLog(@"定位初始化");
//定位管理器
self.locationManager=[[CLLocationManager alloc]init];
//如果没有授权则请求用户授权
if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined ){
[_locationManager requestWhenInUseAuthorization];
}else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedAlways || [CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
//设置代理
_locationManager.delegate=self;
//设置定位精度
// [self.locationManager setAllowsBackgroundLocationUpdates:YES];
_locationManager.desiredAccuracy=kCLLocationAccuracyBest;
_locationManager.pausesLocationUpdatesAutomatically = NO;
//定位频率,每隔多少米定位一次
CLLocationDistance distance = 10;
_locationManager.distanceFilter=distance;
//启动跟踪定位
[_locationManager startUpdatingLocation];
}
}
5.代理方法及地理经纬度转换
#pragma mark - 代理方法相关
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation> *)locations{
CLLocation *currentLoction = [locations lastObject];
/// 得到当前位置的经纬度
self.curCoordinate2D = currentLoction.coordinate;
NSLog(@"定位直接得到的坐标===%f %f",_curCoordinate2D.latitude,_curCoordinate2D.longitude);
[self.locationManager stopUpdatingLocation];
/// 判断当前坐标是否在中国
BOOL isChina = [[ZCChinaLocation shared] isInsideChina:(CLLocationCoordinate2D){_curCoordinate2D.latitude,_curCoordinate2D.longitude}];
if (isChina) {
/// 转换坐标 不转换会出现偏移
_curCoordinate2D = [TQLocationConverter transformFromWGSToGCJ:_curCoordinate2D];
//获得地理位置名字
[self googleMapAddress];
}
}
6.地理经纬度转换后获取相关位置
// 获得地理位置名字
- (NSString *)googleMapAddress{
__block NSString *addressStr;
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
CLLocation *location = [[CLLocation alloc] initWithLatitude:_curCoordinate2D.latitude longitude:_curCoordinate2D.longitude];
NSLog(@"转换后得到的坐标===%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默认显示值
[[NSUserDefaults standardUserDefaults] setObject:city forKey:@"city"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}];
return addressStr;
}
7.点击城市按钮 (单次点击和多次点击,开了定位权限点击和关了定位权限点击)
- (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:@"请去-> [设置 - 隐私 - 定位服务 - 秀贝] 打开访问开关" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//确定按钮点击事件处理
}]];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
二、百度地图(地图视图加搜索附近功能,简易版,未加任何性能优化)
问题:打开百度地图后,发现百度地图显示错误,控制台输出提示引擎初始化失败;此问题还会导致第二次登录进入百度地图控制器界面报错,报错位置在 self.mapView =[[BMKMapView alloc] init];
解决方案:
第一步:
第二步:
卸载真机上的app 重新运行!
0、在百度开放平台注册,导入相关依赖库
1、cocoapods 集成百度地图框架 pod "BaiduMapKit"
2、导入相关头文件
#import <BaiduMapKit/BaiduMapAPI_Map/BMKMapView.h> //mapview 显示相关
#import <BaiduMapKit/BaiduMapAPI_Location/BMKLocationService.h> //定位相关
#import <BaiduMapAPI_Search/BMKGeocodeSearch.h> //geo编码和反geo编码相关
#import <BaiduMapAPI_Search/BMKPoiSearchType.h> //定位信息相关
@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 初始化相关
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;// 先关闭显示的定位图层
_mapView.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态
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编码相关
self.geocodesearch = [[BMKGeoCodeSearch alloc] init];
_geocodesearch.delegate = self;
//初始化tableview列表
self.dataArr = [NSMutableArray array];
[self createMyTableView];
4、内存优化相关
-(void)viewWillAppear:(BOOL)animated
{
[_mapView viewWillAppear];
_mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
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 相关
#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检索发送成功");
}
else
{
NSLog(@"反geo检索发送失败");
}
}
7、#pragma mark - 地图代理相关
/**
*在地图View将要启动定位时,会调用此函数
*/
- (void)willStartLocatingUser
{
NSLog(@"start locate");
}
/**
*用户方向更新后,会调用此函数
*@param userLocation 新的用户位置
*/
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
[self.mapView updateLocationData:userLocation];
// NSLog(@"heading is %@",userLocation.heading);
}
/**
*用户位置更新后,会调用此函数
*@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停止定位后,会调用此函数
*/
- (void)didStopLocatingUser
{
NSLog(@"stop locate");
}
/**
*定位失败后,会调用此函数
*@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
/**
*返回地址信息搜索结果
*@param searcher 搜索对象
*@param result 搜索结BMKGeoCodeSearch果
*@param error 错误号,@see BMKSearchErrorCode
*/
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
NSLog(@"返回地址信息搜索结果,失败-------------");
}
/**
*返回反地理编码搜索结果
*@param searcher 搜索对象
*@param result 搜索结果
*@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)
{
//把当前定位信息自定义组装 放进数组首位
BMKPoiInfo *first =[[BMKPoiInfo alloc]init];
first.address=result.address;
first.name=@"[当前位置]";
first.pt=result.location;
first.city=result.addressDetail.city;
[self.dataArr insertObject:first atIndex:0];
}
[self.tableView reloadData];
}
}