2016-03-01 地图定位 以及失败

.h是这样的

#import <UIKit/UIKit.h>

#import <BaiduMapAPI/BMapKit.h>

@interface NearbyViewController : UIViewController<BMKLocationServiceDelegate,BMKMapViewDelegate>

{

    BMKMapView* _mapView;

    BMKLocationService* _locService;

 

}

@end

 

 

 

 

 .mmmmmm

#import "NearbyViewController.h"

#import "DocDetailViewController.h"

 

@interface NearbyViewController ()<UITableViewDelegate,UITableViewDataSource,BMKGeoCodeSearchDelegate,UIAlertViewDelegate,CLLocationManagerDelegate>

{

    double doustrLat;//经度

    double doustrLng;//纬度

    int number;

    UIImageView *imagershuju;

    UILabel *tiwuxianLab;

    BOOL isLocation;

}

//

 

@property (nonatomic,strong) NSMutableArray *nearMutarr;

@property (nonatomic,strong) UITableView *MYtableview;

@property (nonatomic,strong) BMKGeoCodeSearch *geocodesearch;

@end

 

@implementation NearbyViewController

 

 

-(void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

    number=1;

    

}

- (void)viewDidLoad {

    [super viewDidLoad];

    number=1;

    _nearMutarr = [NSMutableArray array];

    self.title = @"附近专家";

    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"gdback3"] originalImage] style:UIBarButtonItemStylePlain target:self action:@selector(backClick)];

    

    self.navigationItem.leftBarButtonItem=backItem;

    //自定义后退按钮后,手势返回上一级控制器的功能恢复

    self.navigationController.interactivePopGestureRecognizer.delegate = nil;

    [self startLocation];

    

    if (isLocation) {

        _MYtableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];

    }else{

    

        _MYtableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];

 

    }

 

    _MYtableview.delegate =self;

    _MYtableview.dataSource = self;

    _MYtableview.tableFooterView = [[UIView alloc]init];

//    _MYtableview.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.view addSubview:_MYtableview];

    

    imagershuju = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-ImagerWuWidth/2, SCREEN_HEIGHT/2-ImagerWuheight/2, ImagerWuWidth, ImagerWuheight)];

    imagershuju.image = [UIImage imageNamed:@"zanwushuju1"];

//    imagershuju.hidden = YES;

    

    [self.view addSubview:imagershuju];

    tiwuxianLab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-TishiLabwidth/2, CGRectGetMaxY(imagershuju.frame), TishiLabwidth, 30)];

    tiwuxianLab.text = @"附近暂无平台医生";

    tiwuxianLab.textAlignment = YES;

    tiwuxianLab.textColor = RGB(188, 188, 188);

//    tiwuxianLab.hidden = YES;

    tiwuxianLab.font = SYSTEMFONT(TishiLabFont);

    [self.view addSubview:tiwuxianLab];

    [self haderwith];

    [self Downrefresh];

    

    // Do any additional setup after loading the view.

}

//下拉刷新

- (void)Downrefresh

{

    __weak NearbyViewController *puad = self;

    [puad.MYtableview addHeaderWithCallback:^{

        [puad.nearMutarr removeAllObjects];

        number=1;

        [puad locationRequest];

        [puad.MYtableview headerEndRefreshing];

    }];

}

//上拉加载

- (void)haderwith

{

    __weak NearbyViewController *pudb = self;

    [pudb.MYtableview addFooterWithCallback:^{

        number++;

        //        [pudb.Newmuwarr removeAllObjects];

        [pudb locationRequest];

        [pudb.MYtableview footerEndRefreshing];

    }];

}

//定位请求

- (void)locationRequest

{

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    AFHTTPRequestOperationManager *manger = [[AFHTTPRequestOperationManager alloc]init];

    manger.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSString *ssurl = [NSString stringWithFormat:@"%@nearExpert",Public_URL];

    NSMutableDictionary *mudic = [NSMutableDictionary dictionary];

    mudic[@"lat"]=[NSString stringWithFormat:@"%f",doustrLat];

    mudic[@"lng"]=[NSString stringWithFormat:@"%f",doustrLng];

    mudic[@"page"]=[NSString stringWithFormat:@"%d",number];

    [manger POST:ssurl parameters:mudic success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingAllowFragments error:nil];

        NSString *stracode =[NSString stringWithFormat:@"%@",dic[@"code"]];

        if ([stracode isEqualToString:@"1"]) {

            [_nearMutarr addObjectsFromArray:dic[@"data"]];

 

        }else{

            

            UIAlertView *alviec = [[UIAlertView alloc]initWithTitle:@"提示" message:dic[@"message"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

            [alviec show];

            

        }

        if (_nearMutarr.count>0) {

            imagershuju.hidden = YES;

            tiwuxianLab.hidden = YES;

            

        }else{

            imagershuju.hidden = NO;

            tiwuxianLab.hidden = NO;

            

        }

        [MBProgressHUD hideHUDForView:self.view animated:YES];

        [_MYtableview reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [MBProgressHUD hideHUDForView:self.view animated:YES];

        if (_nearMutarr.count>0) {

            imagershuju.hidden = YES;

            tiwuxianLab.hidden = YES;

            

        }else{

            imagershuju.hidden = NO;

            tiwuxianLab.hidden = NO;

            

        }

        [self.MYtableview reloadData];

    }];

 

}

 

- (void)fackbacktionRequest

{

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    AFHTTPRequestOperationManager *manger = [[AFHTTPRequestOperationManager alloc]init];

    manger.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSString *ssurl = [NSString stringWithFormat:@"%@nearExpert",Public_URL];

    NSMutableDictionary *mudic = [NSMutableDictionary dictionary];

    mudic[@"lat"]=[NSString stringWithFormat:@"%f",doustrLat];

    mudic[@"lng"]=[NSString stringWithFormat:@"%f",doustrLng];

    mudic[@"page"]=[NSString stringWithFormat:@"%d",number];

    [manger POST:ssurl parameters:mudic success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingAllowFragments error:nil];

 

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

 

    }];

    

}

 

 

//实现相关delegate 处理位置信息更新

//处理方向变更信息

- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation

{

    //NSLog(@"heading is %@",userLocation.heading);

}

//处理位置坐标更新 2222

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation

{

    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);

    doustrLat=userLocation.location.coordinate.latitude;

    doustrLng = userLocation.location.coordinate.longitude;

//    [self locationRequest];

    [_locService stopUserLocationService];

    

 

    

    

//    CLLocation *c = [[CLLocation alloc] initWithLatitude:doustrLat longitude:doustrLng];

//    //创建位置

//    CLGeocoder *revGeo = [[CLGeocoder alloc] init];

//    [revGeo reverseGeocodeLocation:c

//    completionHandler:^(NSArray *placemarks, NSError *error) {

//                     if (!error && [placemarks count] > 0)

//                     {

//                         NSDictionary *dict =

//                         [[placemarks objectAtIndex:0] addressDictionary]; NSLog(@"street address: %@",

//                                                                                 //记录地址  

//                                                                                 [dict objectForKey:@"Street"]); }  

//                     else  

//                     {  

//                         NSLog(@"ERROR: %@", error); }  

//                 }];

    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude};

     _geocodesearch = [[BMKGeoCodeSearch alloc]init];

    _geocodesearch.delegate = self;

    //发起反向地理编码检索

    //    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){39.915, 116.404};

    BMKReverseGeoCodeOption *reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];

    //需要逆地理编码的坐标位置

    reverseGeoCodeOption.reverseGeoPoint = pt;

    [_geocodesearch reverseGeoCode:reverseGeoCodeOption];

    

    [self locationRequest];

}

 

- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error

{

    NSLog(@"------=====3333=解析编码信息%@",result);

    //BMKReverseGeoCodeResult是编码的结果,包括地理位置,道路名称,uid,城市名等信息

    if (error == 0) {

        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];

        item.coordinate = result.location;

        item.title = result.address;

        //

        NSString *prostr = result.addressDetail.province;

        NSString *cityName =  result.addressDetail.city;

        //        result.addressDetail

        /** ,*/

        NSString *district = result.addressDetail.district;

        

        //        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];

//        [user setObject:cityName forKey:@"CityName"];

//        [user setObject:district forKey:@"McRegion"];

//        

//        if (cityName.length !=0)

//        {

//            [user setObject:@"郑州市" forKey:@"CityName"];

//            

//        }

        

        

        //        [_mapView addAnnotation:item];

        //        _mapView.centerCoordinate = result.location;

        MCLog(@" %@-城市%@--区-%@",prostr,cityName,district);

        [_locService stopUserLocationService];

    }

    

}

 

 

 

 

 

 

 

//定位

- (void)startLocation

{

    

    if ([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied){

    

        isLocation=YES;

        //    MBProgressHUD *hub = [[MBProgressHUD alloc] initWithView:self.view];

        //

        //    hub.labelText = @"定位中";

        MBProgressHUD *hub = [[MBProgressHUD alloc] initWithView:self.view];

        

        hub.labelText = @"定位中";

        

        //    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

        [self.view addSubview:hub];

        [hub show:YES];

        //设置定位精确度,默认:kCLLocationAccuracyBest

        [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];

        //指定最小距离更新(),默认:kCLDistanceFilterNone

        [BMKLocationService setLocationDistanceFilter:100.f];

        

        //初始化BMKLocationService

        _locService = [[BMKLocationService alloc]init];

        _locService.delegate = self;

        //启动LocationService

        [_locService startUserLocationService];

        //普通态

        

        //    _mapView.showsUserLocation = NO;//先关闭显示的定位图层

        //    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态

        //    _mapView.showsUserLocation = YES;//显示定位图层

    

    }else{

        isLocation=NO;

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示!" message:@"需要开启定位服务,请到设置->隐私,打开定位服务 肝胆相照->使用应用期间" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];

        

        [alertView show];

    

    }

 

}

 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

//    return 110;

    return 95;

 

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

 

    return _nearMutarr.count;

 

 

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

 

{

    static NSString *cellIn=@"cell";

    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIn ];

    if (!cell) {

        

        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIn];

        

    }

    for (UIView *view in cell.contentView.subviews) {

        [view removeFromSuperview];

    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (_nearMutarr.count>0) {

        [cell.contentView addSubview:[self CellFview:(int)indexPath.row]];

 

    }

    return cell;

 

}

- (UIView *)CellFview:(int)cellsend

{    NSDictionary *diccell = [self clearErrorData:_nearMutarr[cellsend]];

 

    

    UIView *packagingView11 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 95)];

 

    

    

    

    

    UIImageView *imagevieHear = [[UIImageView alloc]initWithFrame:CGRectMake(15, 15+5, 54, 54)];

    NSString *hearImagecell = [NSString stringWithFormat:@"%@%@",ImageUrl,diccell[@"photo"]];

    [imagevieHear sd_setImageWithURL:[NSURL URLWithString:hearImagecell] placeholderImage:[UIImage imageNamed:@"huisetouxiangfu"]];

    imagevieHear.layer.cornerRadius = 27;

    imagevieHear.layer.masksToBounds = YES;

    [packagingView11 addSubview:imagevieHear];

    UIButton *buttonimage  = [UIButton buttonWithType:UIButtonTypeCustom];

    buttonimage.frame = CGRectMake(15, 15, 54, 54);

    //    [buttonimage setBackgroundImage:[UIImage imageNamed:@"hearn"] forState:0];

    [buttonimage addTarget:self action:@selector(imageBtn:) forControlEvents:UIControlEventTouchUpInside];

    buttonimage.tag = cellsend;

    [imagevieHear addSubview:buttonimage];

    

    

    //姓名

    NSString *realName=[diccell objectForKey:@"realName"];

    

    UILabel *nameLabel=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imagevieHear.frame)+12,15,80,17)];

    nameLabel.textAlignment=NSTextAlignmentLeft;

    nameLabel.font=[UIFont systemFontOfSize:15];

    nameLabel.text=realName;

    

    [nameLabel sizeToFit];

    [packagingView11 addSubview:nameLabel];

    

    //头衔

    NSString *positionName=[diccell objectForKey:@"positionName"];

    UILabel *touxianLabel=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imagevieHear.frame)+12, CGRectGetMaxY(nameLabel.frame)+10, 120, 15)];

    touxianLabel.font=[UIFont systemFontOfSize:13];

    touxianLabel.textColor=[UIColor grayColor];

    touxianLabel.text=positionName;

    [touxianLabel sizeToFit];

    //    _touxianLabel.backgroundColor=[UIColor blueColor];

    [packagingView11 addSubview:touxianLabel];

    //地址

    NSString *hospitalName=[diccell objectForKey:@"hospitalName"];

   UILabel *addressLabel=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imagevieHear.frame)+12, CGRectGetMaxY(touxianLabel.frame)+10, 120, 15)];

    addressLabel.font=[UIFont systemFontOfSize:13];

    addressLabel.textColor=[UIColor grayColor];

    addressLabel.text=hospitalName;

    [addressLabel sizeToFit];

    [packagingView11 addSubview:addressLabel];

    

    

    //擅长

    NSString *specialities=[diccell objectForKey:@"officeName"];

    UILabel *goodatLabel=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(addressLabel.frame)+12, CGRectGetMaxY(addressLabel.frame)+10, 120, 15)];

    goodatLabel.font=[UIFont systemFontOfSize:13];

    goodatLabel.textColor=[UIColor grayColor];

    goodatLabel.text=specialities;

    goodatLabel.centerY=addressLabel.centerY;

    [goodatLabel sizeToFit];

    //    _goodatLabel.backgroundColor=[UIColor blueColor];

    [packagingView11 addSubview:goodatLabel];

    

    

    NSString *strcall = [NSString stringWithFormat:@"%@",diccell[@"callIsEnable"]];

    UIImageView *imagecall = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-80, 15, 15, 15)];

    if ([strcall isEqualToString:@"1"]) {

        imagecall.image   = [UIImage imageNamed:@"callliang"];

 

    }else{

        imagecall.image   = [UIImage imageNamed:@"doccall"];

 

    }

    [packagingView11 addSubview:imagecall];

    

    

    

    NSString *strclicer = [NSString stringWithFormat:@"%@",diccell[@"clinicIsEnable"]];

    UIImageView *imageclicer = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imagecall.frame)+10, 15, 12, 15)];

    if ([strclicer isEqualToString:@"1"]) {

        imageclicer.image   = [UIImage imageNamed:@"xiaorenliang"];

        

    }else{

        imageclicer.image   = [UIImage imageNamed:@"xiaoren"];

        

    }

    [packagingView11 addSubview:imageclicer];

    

    

    

    NSString *strmonter = [NSString stringWithFormat:@"%@",diccell[@"monthIsEnable"]];

    UIImageView *imagemonter = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imageclicer.frame)+10, 15, 15, 15)];

    if ([strmonter isEqualToString:@"1"]) {

        imagemonter.image  = [UIImage imageNamed:@"vliang"];

        

    }else{

        imagemonter.image  = [UIImage imageNamed:@"vgarner"];

        

    }

    [packagingView11 addSubview:imagemonter];

    

 

    

    return packagingView11;

    

    

    

}

 

 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    DocDetailViewController  *docD=[[DocDetailViewController alloc]init];

    docD.strDocuuid = [_nearMutarr[indexPath.row] objectForKey:@"uuid"];

    [self.navigationController pushViewController:docD animated:YES];

}

 

- (void)NercallClickk:(UIButton *)sender

{

 

    

}

- (void)NerxiaorentouClickk:(UIButton *)sender

{

    

    

}

- (void)NerVClickk:(UIButton *)sender

{

    

}

 

 

 

- (void)imageBtn:(UIButton *)buttnDer

{

    DocDetailViewController  *docD=[[DocDetailViewController alloc]init];

    docD.strDocuuid = [_nearMutarr[buttnDer.tag] objectForKey:@"uuid"];

    [self.navigationController pushViewController:docD animated:YES];

}

 

 

-(NSDictionary *)clearErrorData:(NSMutableDictionary *)dictionary{

    

    NSMutableDictionary  *newDict = [[NSMutableDictionary alloc] initWithDictionary:dictionary]

    ;

    NSArray * allkeys = [newDict allKeys];

    for (int i = 0; i < [allkeys count]; i ++) {

        // 获取下标对应的key

        NSString * key = [allkeys objectAtIndex:i];

        // 根据key获取value

        NSString * value = [newDict objectForKey:key];

        if (value == [NSNull null]) {

            newDict[key] = @"";

        }

    }

    return newDict;

}

 

-(void)backClick{

    

    [self.navigationController  popViewControllerAnimated:YES];

    

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

 

////gzz0301百度地图

//-(void)didFailToLocateUserWithError:(NSError *)error{

//

//

//    NSString *errorString;

//    [_locService stopUserLocationService];

//    NSLog(@"Error: %@",[error localizedDescription]);

//    switch([error code]) {

//        case kCLErrorDenied:

//            //Access denied by user

////            errorString = @"Access to Location Services denied by user";

//            errorString = @"请在设置中将该应用程序的位置更改为\"使用应用期间\"";

//            break;

//        case kCLErrorLocationUnknown:

//            //Probably temporary...

////            errorString = @"Location data unavailable";

//            errorString = @"定位数据不可用";

//

//            break;

//        default:

////            errorString = @"An unknown error has occurred";

//            errorString = @"出现未知错误";

//

//            break;

//            

//    }

//    

//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:errorString delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

//    [alert show];

//

//

//

//

//}

//

//

////系统的 定位失败

//-(void)locationManager: (CLLocationManager *)manager

//       didFailWithError: (NSError *)error {

//    

//    NSString *errorString;

//    [manager stopUpdatingLocation];

//    NSLog(@"Error: %@",[error localizedDescription]);

//    switch([error code]) {

//        case kCLErrorDenied:

//            //Access denied by user

//            errorString = @"Access to Location Services denied by user";

//            //Do something...

//            break;

//        case kCLErrorLocationUnknown:

//            //Probably temporary...

//            errorString = @"Location data unavailable";

//            //Do something else...

//            break;

//        default:

//            errorString = @"An unknown error has occurred";

//            break;

//    

//    }

//    

//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

//    [alert show];

//    

//}

//

 

//}

 

 

//开始定位

//

//- (void)startLocation

//

//{

//    

//    if ([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {

//        

//        //设置代理

//        

//        _locationManager = [[CLLocationManager alloc] init];

//        

//        _locationManager.delegate = self;

//        

//        //设置定位精度

//        

//        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;

//        

//        //多远定位依次

//        

//        _locationManager.distanceFilter = 100;

//        

//        //ios8

//        

//        if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){

//            

//            [_locationManager requestAlwaysAuthorization];

//            

//        }

//        

//        //启动

//        

//        [_locationManager startUpdatingLocation];

//        

//    }else

//        

//    {

//        

//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示!" message:@"需要开启定位服务,请到设置->隐私,打开定位服务 肝胆相照->使用应用期间" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];

//        

//        [alertView show];

//        

//    }

 

 

 

@end

posted @ 2016-03-01 14:07  zhen_zhen  阅读(282)  评论(0编辑  收藏  举报