首页 > 其他分享 >ios如何集成百度地图---还是自己动手做一下--网上好多博客说的都不甚靠谱。

ios如何集成百度地图---还是自己动手做一下--网上好多博客说的都不甚靠谱。

时间:2023-05-09 23:31:46浏览次数:47  
标签:动手做 alloc nil -- NSLog self 甚靠 mapView void

1:申请key,在appdelegate中加入相应的代码。比如。
      appdelegate.h中:
     
#import <UIKit/UIKit.h>
#import <FMDB.h>
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件

#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件

@interface AppDelegate :  UIResponder <UIApplicationDelegate>
{
    BMKMapManager *_mapManager;
}
@property (nonatomic,strong)NSMutableArray *contactsArray;
@property (strong,nonatomic) UIWindow *window;
@property (nonatomic,strong)FMDatabase * db;
@end


在appdelegate.m中增加对应的初始化:
 //百度地图
    _mapManager = [[BMKMapManageralloc]init];
    // 如果要关注网络及授权验证事件,请设定     generalDelegate参数
    BOOL ret = [_mapManagerstart:@"xxxxxxxxxxxxx" generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
 注:这个xxxxxxxx是自己当时申请的。 
如果在appdelegate里面不增加的话,就会导致整个程序页面假死,程序不崩溃就是直接僵死在那儿,而且还会影响到整个手机的性能。
2:info.plist中需要增加两个字段()
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
字段需要增加,但是值的话可以为空。-----这两个字段如果不加的话,会出现百度地图总是自动定位到北京天安门的问题。--天安门上红旗飘~~~~~~
3:地图控制器的代码
.h代码
#import <UIKit/UIKit.h>

#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件
#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
@interface LocationViewController : UIViewController{

    BMKMapManager *_mapManager;
}

@property (nonatomic,copy) NSString * titleString;
@end
 .m代码 
//
//  LocationViewController.m
//  TeamTalk
//

#import "common.h"
#import "LocationViewController.h"
#import "LocationRecordViewController.h"
@interface LocationViewController ()<BMKMapViewDelegate,BMKPoiSearchDelegate,BMKLocationServiceDelegate,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
@property (nonatomic,strong) BMKMapView * mapView;
@property (nonatomic,strong) BMKPoiSearch * searcher;
@property (nonatomic,strong) BMKLocationService * locService;
@property (nonatomic,strong) BMKPointAnnotation * annotation;
@property (nonatomic,strong) UITableView * myTabelView;
@property (nonatomic,strong) NSMutableArray * nameArray;
@property (nonatomic,copy) NSString * alertViewMessageString;
@property (nonatomic,copy) NSString * customId;
@property (nonatomic,strong) BMKNearbySearchOption *option;
@property (nonatomic,strong) MBProgressHUD* hud;
@end

@implementation LocationViewController

#pragma mark - lazy
-(NSMutableArray *)nameArray{
    
    if (_nameArray == nil) {
        _nameArray = [[NSMutableArray alloc]init];
    }
    
    return _nameArray;
}

-(BMKPointAnnotation *)annotation{
    
    if (!_annotation) {
        _annotation = [[BMKPointAnnotation alloc]init];
    }
    return _annotation;
}

#pragma mark - life circle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = _titleString;
    self.view.backgroundColor = BACKGROUNDCOLOR;
    [self initializationMapService];
    [self initializationMyTableView];
}
-(void)viewWillAppear:(BOOL)animated{
    [_mapView viewWillAppear];
    _mapView.delegate = self; //  此处记得不用的时候需要置nil,否则影响内存的释放
    UIBarButtonItem *recordItem = [[UIBarButtonItem alloc]initWithTitle:@"记录" style:UIBarButtonItemStylePlain target:self action:@selector(viewTheReecords)];
    self.navigationItem.rightBarButtonItem = recordItem
}

-(void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; //  不用时,置nil
    
    _searcher = nil;
    _searcher.delegate = nil;
    
    self.navigationItem.rightBarButtonItem = nil;
}


#pragma mark - targets
-(void)viewTheReecords{
    
    LocationRecordViewController *recoreVC = [[LocationRecordViewController alloc]init];
    [self.navigationController pushViewController:recoreVC  animated:YES];
    
}


#pragma mark - initialization Map
-(void)initializationMapService{
    
    _mapView =[[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen]bounds].size.width,[[UIScreen mainScreen]bounds].size.height / 5 * 3 )];
    _mapView.delegate = self;
    [self.view addSubview:_mapView];
    _mapView.zoomLevel = 19;
    
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
    
    [_mapView setShowMapPoi:YES];
    
    //初始化检索对象
    _searcher =[[BMKPoiSearch alloc]init];
    _searcher.delegate = self;
    
    

    
}

#pragma mark - initialization tableView
-(void)initializationMyTableView{
    
    _myTabelView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    _myTabelView.delegate = self;
    _myTabelView.dataSource = self;
    [self.view addSubview:_myTabelView];
    [_myTabelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_mapView.mas_bottom);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    _mapView.backgroundColor = [UIColor blueColor];
    
}

#pragma mark - tableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _nameArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellId = @"LocationCell";
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    if (cell == nil) {
        cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    }
    cell.textLabel.text = _nameArray[indexPath.row];
    
    //    NSLog(@"名字 = %@",_nameArray[indexPath.row]);
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    NSLog(@"cell = %@",cell.textLabel.text);
    
    //无权限
    if (([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"签到位置" message:cell.textLabel.text preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *certainAction = [UIAlertAction actionWithTitle:@"签到" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSDate *date = [NSDate date];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT+0800"];
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *destDateString = [dateFormatter stringFromDate:date];
            
            
            NSLog(@"点击签到----%@-",destDateString);
            
            
            [self uploadWithTimeString:destDateString locationString:cell.textLabel.text];
        }];
        
        [alertController addAction:certainAction];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
        return;
        
    }else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"签到位置" message:cell.textLabel.text delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"签到", nil];
        _alertViewMessageString = cell.textLabel.text;
        [alertView show];
        return;
    }
}

#pragma mark - 点击签到
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        NSLog(@"点击取消");
        
    }else if (buttonIndex == 1){//签到动作
        
        NSString *dateString = [[NSString alloc]initWithFormat:@"%@",[NSDate date]];
        NSLog(@"点击签到----%@-",dateString);
        [self uploadWithTimeString:dateString  locationString:_alertViewMessageString];
    }
}

#pragma mark - 地理位置更新处理
//实现相关delegate 处理位置信息更新
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation{
    
    //普通态
    //以下_mapView为BMKMapView对象
    _mapView.showsUserLocation = YES;//显示定位图层
    [_mapView updateLocationData:userLocation];
    
    // 添加一个PointAnnotation
    CLLocationCoordinate2D coor;
    
    coor.latitude = userLocation.location.coordinate.latitude;
    coor.longitude = userLocation.location.coordinate.longitude;
    _annotation.coordinate = coor;
    [_mapView addAnnotation:_annotation];
    
    
    
}

//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    
    //发起检索
    _option = [[BMKNearbySearchOption alloc]init];
    _option.pageCapacity = 20;
    _option.location = CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    _option.keyword = @"街道,大楼";
    BOOL flag = [_searcher poiSearchNearBy:_option];
    if(flag)
    {
        NSLog(@"周边检索发送成功");
    }
    else
    {
        [self showHUDWithHUDString:@"位置信息获取失败"];
        NSLog(@"周边检索发送失败");
    }
    
    _mapView.centerCoordinate =  userLocation.location.coordinate;
}

#pragma mark - poi地址查询回调\//实现PoiSearchDeleage处理回调结果
- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPoiResult*)poiResultList errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果]
        //NSLog(@"poi地址 %@",poiResultList);
        NSMutableArray *arr = [NSMutableArray array];
        for (BMKPoiInfo *info in poiResultList.poiInfoList) {
            
            [arr addObject:info.name];
        }
        _nameArray = arr;
        //        NSLog(@"姓名数组= %@",_nameArray);
        
        [_myTabelView reloadData];
        
    }
    else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD){
        //当在设置城市未找到结果,但在其他城市找到结果时,回调建议检索城市列表
        // result.cityList;
        NSLog(@"起始点有歧义");
    } else {
        NSLog(@"抱歉,未找到结果");
    }
}
#pragma mark - 数据库操作
//生成网络请求的参数
-(NSMutableDictionary *)makePostParamsWithTimestring:(NSString *)timestring locationString:(NSString *)locationString{
    
    
    CFUUIDRef uuidObj = CFUUIDCreate(nil);
    NSString *uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(nil, uuidObj));
    
    AppDelegate *myDelegate = [[UIApplication sharedApplication]delegate];
    
    if([myDelegate.db open]){
        NSLog(@"打开成功");
        
        //基本信息表
        [myDelegate.db beginTransaction];
        FMResultSet *result = [myDelegate.db executeQuery:@"select * from custom001 where (seller_id = '003' )"];
        while ([result next]) {
            
            _customId = [result stringForColumn:@"id"];
            NSLog(@"customId is %@",_customId);
        }
        
    }else{
        NSLog(@"打开失败");
        
    }
    [myDelegate.db close];
    
    
    
    NSMutableDictionary *mutDict = [[NSMutableDictionary alloc]init];
    [mutDict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"] forKey:@"user_id"];
    [mutDict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] forKey:@"token"];
    [mutDict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"e_token"] forKey:@"e_token"];
    [mutDict setObject:@"insert" forKey:@"app_action"];
    [mutDict setObject:@"custom1023" forKey:@"app_table"];
    NSDictionary *dict = @{@"seller_id":@"608",
                           @"reserve1":timestring,
                           @"reserve2":locationString,
                           @"reserve11":_customId,
                           @"created_at":timestring,
                           @"updated_at":timestring,
                           @"id":uuidString};
    
    [mutDict setObject:dict forKey:@"app_data"];
    
    return mutDict;
    
}

//生成原生网络请求
-(NSURLRequest *)makePostRequest:(NSMutableDictionary *)mutDict{
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mutDict  options:NSJSONWritingPrettyPrinted error:&parseError];
    //创建请求
    NSURL *url = [NSURL URLWithString:@"http://crm.fumiduo.com/app_global_new/app_insert"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    
    //设置请求头
    [request setValue:@"applocation/json" forHTTPHeaderField:@"Content-Type"];
    request.HTTPBody = jsonData;
    
    return request;
    
}


#pragma mark 存储
#pragma mark 上传
- (void)uploadWithTimeString:(NSString *)timeString locationString:(NSString *)locationString{
    
    
    
    NSMutableDictionary *mutDict = [self makePostParamsWithTimestring:timeString locationString:locationString];
    
    NSURLRequest *request  = [self makePostRequest:mutDict];
    
    NSLog(@"参数 = %@",mutDict);
    
    [NSURLConnection sendAsynchronousRequest:request  queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"返回的参数dict is %@---",dict);
        
    }];
    
}

#pragma mark - HUD
- (void)showHUDWithHUDString:(NSString *)string{
    
    _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _hud.mode = MBProgressHUDModeText;
    _hud.labelText = string;
    _hud.removeFromSuperViewOnHide = YES;
    [_hud hide:YES afterDelay:2];
}

#pragma mark - 大头针
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
        newAnnotationView.animatesDrop = YES;//  设置该标注点动画显示
        return newAnnotationView;
    }
    return nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

标签:动手做,alloc,nil,--,NSLog,self,甚靠,mapView,void
From: https://blog.51cto.com/u_16105066/6260080

相关文章

  • 判断应用是否有访问相册和相机的权限
    1:导入avfoundtion框架pch中导入头文件#import<AVFoundation/AVCaptureDevice.h>#import<AVFoundation/AVMediaFormat.h>#import<AssetsLibrary/AssetsLibrary.h>2:判断的代码if(sourceType==UIImagePickerControllerSourceTypePhotoLibrary){判断相册权限......
  • 算法学习day09字符串part02-28、459--待办
    packageLeetCode.stringpart02;/***28.找出字符串中第一个匹配项的下标*给你两个字符串haystack和needle,请你在haystack字符串中找出needle字符串的第一个匹配项的下标(下标从0开始)。*如果needle不是haystack的一部分,则返回-1。*实例:*输入:hayst......
  • 打卡10
    #include<iostream>usingnamespacestd;voidshz(int*arr,intlen){ for(inti=0;i<len-1;i++) { for(intj=0;j<len-1-i;j++) { if(arr[j]<arr[j+1]) { inttemp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } }} voidshz2(int*arr,intl......
  • Linux的这七大认识误区,你千万别有!
    本文罗列了大家对Linux的七大认识误区,看看其中那个是你也出现过的。千万别让这些先入为主的观点断送了你体验新事物的机会。Linux的受众群体并不大。对还是错?错!大错而特错。我承认,Linux的实际用户数量很难统计,因为其免费开放下载且并未由单一企业进行控制。没有明确的销......
  • Linux的这七大认识误区,你千万别有!
    本文罗列了大家对Linux的七大认识误区,看看其中那个是你也出现过的。千万别让这些先入为主的观点断送了你体验新事物的机会。Linux的受众群体并不大。对还是错?错!大错而特错。我承认,Linux的实际用户数量很难统计,因为其免费开放下载且并未由单一企业进行控制。没有明确的销......
  • Linux的这七大认识误区,你千万别有!
    本文罗列了大家对Linux的七大认识误区,看看其中那个是你也出现过的。千万别让这些先入为主的观点断送了你体验新事物的机会。Linux的受众群体并不大。对还是错?错!大错而特错。我承认,Linux的实际用户数量很难统计,因为其免费开放下载且并未由单一企业进行控制。没有明确的销......
  • Failed to open connection to "session" message bus: Using X11 for dbus-daemon au
    Failedtoopenconnectionto"session"messagebus:UsingX11fordbus-daemonautolaunchwasdisabledatcompiletime,setyourDBUS_SESSION_BUS_ADDRESSinstead4Failedtoopenconnectionto"session"messagebus:UsingX11fordbus-da......
  • fetchone()和fetchall()
    最近写小程序久违的用到了数据库,用fetch()返回数据库搜索的数据时却犯了个低级错误。我本来只是获取一条数据,调用了fetchall(),想将数据转化为列表,却发现列表里的数据仍是元组cursor.execute(sql)res=list(cursor.fetchall())print(res) 想了一会用元组解包还是没用,原来......
  • 团队绩效管理
                                                          团队绩效考核无敌三人组姓名任务确立(10)任务完成度(10)工作态度(10)工作积极性(10)责任心(10)团队合作(10......
  • python 小技巧, 如何找到多个字典中的公共键(key)
    ......