iOS调用百度地图踩坑(一)

1.阅读百度地图官方文档
2.配置调用百度地图的环境
3.实现地图的调用
4.下面的代码主要实现了传入省市,能定位到选择的省市区域 ,可设置蒙版,然后点击地图上的一个建筑物能拿到点击的地理位置。
5.得到的就是选择的地址。

NSString *address = [NSString stringWithFormat:@"%@%@",self.addressText,self.addressText1];

代码

//    百度地图
    // 要使用百度地图,请先启动BaiduMapManager
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件,请设定     generalDelegate参数
    BOOL ret = [_mapManager start:BaiduAppKey  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
@interface LogingMapViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKDistrictSearchDelegate,BMKGeoCodeSearchDelegate>
{
    BMKLocationService * _locService;
}
@property (nonatomic,strong)NSString *cityText;//传入地图的省
@property (nonatomic,strong)NSString *provinceText;//传入地图的市

@property (nonatomic, strong) BMKMapView *mapView; // 地图
@property (nonatomic, strong) BMKLocationService *locService; // 位置
@property (nonatomic, strong) BMKDistrictSearch  *districtSearch; // 检索
@property (nonatomic, strong) BMKPointAnnotation *pointAnnotation;
@property (nonatomic, strong) BMKReverseGeoCodeOption *reGeo;
@property (nonatomic, strong) BMKGeoCodeSearch *searchAddress;

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.delegate = self;
    _districtSearch.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
}

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

#pragma mark ****************百度地图相关****************```
- (void)setupMapView
{
    /* 地图 */
    _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(20 *kScale, 230 *kScale, 710 *kScale, 784 *kScale)];
    [self.view addSubview:_mapView];
    //    _mapView.mapType = BMKMapTypeNone;
    _mapView.showMapScaleBar = YES;//显示比例尺
    _mapView.zoomLevel=17;//地图显示的级别
    
    /* 检索 */
    //适配ios7
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        //        self.edgesForExtendedLayout=UIRectEdgeNone;
        self.navigationController.navigationBar.translucent = NO;
    }
    
    _districtSearch = [[BMKDistrictSearch alloc] init];
    
    /* 位置 */
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    _searchAddress = [[BMKGeoCodeSearch alloc] init];
    _searchAddress.delegate = self;
}

/**
 *用户位置更新后,会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    
    BMKCoordinateRegion region;
    
    region.center.latitude  = userLocation.location.coordinate.latitude;
    region.center.longitude = userLocation.location.coordinate.longitude;
    region.span.latitudeDelta = 0;
    region.span.longitudeDelta = 0;
    
    JMLog(@"当前的坐标是:%f,%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    [_mapView updateLocationData:userLocation];
    [_locService stopUserLocationService];//取消定位  这个一定要写,不然无法移动定位了
    _mapView.centerCoordinate = userLocation.location.coordinate;
    JMLog(@" _mapView.centerCoordinate------%f-----%f", _mapView.centerCoordinate.latitude, _mapView.centerCoordinate.longitude);
    if (_messageView == nil && _locationView == nil) {
    
    }
    
}

/** ==================================标注======================================== **/

/**
 *点中底图空白处会回调此接口
 *@param mapView 地图View
 *@param coordinate 空白处坐标点的经纬度
 */
-(void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate
{
    NSLog(@"onClickedMapBlank-latitude==%f,longitude==%f",coordinate.latitude,coordinate.longitude);
    NSString* showmeg = [NSString stringWithFormat:@"您点击了地图空白处(blank click).\r\n当前经度:%f,当前纬度:%f,\r\nZoomLevel=%d;RotateAngle=%d;OverlookAngle=%d", coordinate.longitude,coordinate.latitude,(int)_mapView.zoomLevel,_mapView.rotation,_mapView.overlooking];
    
    // 点击之前删除所有标注
    NSArray * arrAnimation = [[NSArray alloc] initWithArray:_mapView.annotations];
    [_mapView removeAnnotations:arrAnimation];
    // 取消编辑
//    [_cityTF resignFirstResponder];
//    [_provinceTF resignFirstResponder];
    
    // 添加标注
    [self addPointAnnotation:coordinate];
}

/**
 * 点击地图上面建筑物标记事件,有建筑物的位置点击事件
 */
-(void)mapView:(BMKMapView *)mapView onClickedMapPoi:(BMKMapPoi *)mapPoi
{
    self.addressText1 = mapPoi.text;
    JMLog(@"点击onClickedMapPoi---%@",mapPoi.text);

    CLLocationCoordinate2D coordinate = mapPoi.pt;
    // 点击之前删除所有标注
    NSArray * arrAnimation = [[NSArray alloc] initWithArray:_mapView.annotations];
    [_mapView removeAnnotations:arrAnimation];
    //添加标注
    [self addPointAnnotation:coordinate];
}

#pragma mark 添加标注
-(void)addPointAnnotation:(CLLocationCoordinate2D)coordinate
{
    // 添加一个PointAnnotation
    _pointAnnotation = [[BMKPointAnnotation alloc]init];
    CLLocationCoordinate2D coor;
    coor.latitude = coordinate.latitude;
    coor.longitude = coordinate.longitude;
    _pointAnnotation.coordinate = coor;
    _pointAnnotation.title = @"地址:";
    [_mapView addAnnotation:_pointAnnotation];
    
    ///反geo检索信息类
    _reGeo = [[BMKReverseGeoCodeOption alloc]init];
    _reGeo.reverseGeoPoint = coor;
    [_searchAddress reverseGeoCode:_reGeo];
    BOOL flag = [_searchAddress reverseGeoCode:_reGeo];
    if (!flag) {
        NSLog(@"search failed!");
    }
}


/** ==================================检索======================================== **/
#pragma mark ************点击检索***************
- (void)clickdistrictSearch
{
    [self.view endEditing:YES];
    
    BMKDistrictSearchOption *option = [[BMKDistrictSearchOption alloc] init];
//    传入检索条件 省市text
    option.city = _provinceText;
    option.district = _cityText;
    BOOL flag = [_districtSearch districtSearch:option];
    if (flag) {
        NSLog(@"district检索发送成功");
    } else {
        NSLog(@"district检索发送失败");
    }
}

/**
 *返回行政区域搜索结果
 *@param searcher 搜索对象
 *@param result 搜索结BMKDistrictSearch果
 *@param error 错误号,@see BMKSearchErrorCode
 */
- (void)onGetDistrictResult:(BMKDistrictSearch *)searcher result:(BMKDistrictResult *)result errorCode:(BMKSearchErrorCode)error {
    NSLog(@"onGetDistrictResult error: %d", error);
    NSArray *overlayArray = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:overlayArray];
    if (error == BMK_SEARCH_NO_ERROR) {
        NSLog(@"\nname:%@\ncode:%d\ncenter latlon:%lf,%lf", result.name, (int)result.code, result.center.latitude, result.center.longitude);
        
        BOOL flag = YES;
        for (NSString *path in result.paths) {
            BMKPolygon* polygon = [self transferPathStringToPolygon:path];
            if (polygon) {
                [_mapView addOverlay:polygon]; // 添加overlay
                if (flag) {
                    [self mapViewFitPolygon:polygon];
                    flag = NO;
                }
            }
        }
    }
}
#pragma mark - ***********设置选中地的蒙版*********** 可注释掉
//- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
//{
//    if ([overlay isKindOfClass:[BMKPolygon class]]) {
//        BMKPolygonView *polygonView = [[BMKPolygonView alloc] initWithOverlay:overlay];
//        polygonView.strokeColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.6];
//        polygonView.fillColor = [UIColor colorWithRed:1 green:1 blue:0 alpha:0.4];
//        polygonView.lineWidth = 1;
//        polygonView.lineDash = YES;
//        return polygonView;
//    }
//    return nil;
//}

//根据polygone设置地图范围
- (void)mapViewFitPolygon:(BMKPolygon *) polygon {
    CGFloat leftTopX, leftTopY, rightBottomX, rightBottomY;
    if (polygon.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polygon.points[0];
    // 左上角顶点
    leftTopX = pt.x;
    leftTopY = pt.y;
    // 右下角顶点
    rightBottomX = pt.x;
    rightBottomY = pt.y;
    for (int i = 1; i < polygon.pointCount; i++) {
        BMKMapPoint pt = polygon.points[i];
        leftTopX = pt.x < leftTopX ? pt.x : leftTopX;
        leftTopY = pt.y < leftTopY ? pt.y : leftTopY;
        rightBottomX = pt.x > rightBottomX ? pt.x : rightBottomX;
        rightBottomY = pt.y > rightBottomY ? pt.y : rightBottomY;
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(leftTopX, leftTopY);
    rect.size = BMKMapSizeMake(rightBottomX - leftTopX, rightBottomY - leftTopY);
    UIEdgeInsets padding = UIEdgeInsetsMake(30, 0, 100, 0);
    BMKMapRect fitRect = [_mapView mapRectThatFits:rect edgePadding:padding];
    [_mapView setVisibleMapRect:fitRect];
}
- (BMKPolygon*)transferPathStringToPolygon:(NSString*) path {
    if (path == nil || path.length < 1) {
        return nil;
    }
    NSArray *pts = [path componentsSeparatedByString:@";"];
    if (pts == nil || pts.count < 1) {
        return nil;
    }
    BMKMapPoint *points = new BMKMapPoint[pts.count];
    NSInteger index = 0;
    for (NSString *ptStr in pts) {
        if (ptStr && [ptStr rangeOfString:@","].location != NSNotFound) {
            NSRange range = [ptStr rangeOfString:@","];
            NSString *xStr = [ptStr substringWithRange:NSMakeRange(0, range.location)];
            NSString *yStr = [ptStr substringWithRange:NSMakeRange(range.location + range.length, ptStr.length - range.location - range.length)];
            if (xStr && xStr.length > 0 && [xStr respondsToSelector:@selector(doubleValue)]
                && yStr && yStr.length > 0 && [yStr respondsToSelector:@selector(doubleValue)]) {
                points[index] = BMKMapPointMake(xStr.doubleValue, yStr.doubleValue);
                index++;
            }
        }
    }
    BMKPolygon *polygon = nil;
    if (index > 0) {
        polygon = [BMKPolygon polygonWithPoints:points count:index];
    }
    delete [] points;
    return polygon;
}



/** ==================================街道======================================== **/

#pragma mark 根据经纬度返回点击的位置的名称
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
//    得到点击的位置
    JMLog(@"%@",result.address);
    self.addressText = result.address;
    _pointAnnotation.subtitle = result.address;
    
    //    UIAlertController * alert = [UIAlertController alertControllerWithTitle:result.address message:nil preferredStyle:UIAlertControllerStyleAlert];
    //    UIAlertAction * action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    //    [alert addAction:action];
    //    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark 店家annotation弹出的泡泡时,调用
-(void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view
{
    NSLog(@"点击泡泡");
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,049评论 5 473
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,478评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,109评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,097评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,115评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,280评论 1 279
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,748评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,398评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,553评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,440评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,487评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,176评论 3 317
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,750评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,821评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,049评论 1 257
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,559评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,150评论 2 341

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,985评论 4 60
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,297评论 25 707
  • 娘娘腔名叫魏保亚,因说话时无论嗓音,语调,动作,还是神态,都缺乏男子汉的阳刚气而得名。 印象中他是从外边转到我们班...
    疏林红叶阅读 471评论 25 22
  • 2017年的今天是一个特别的日子,我所开发的全网独创的TTT动画版微课,在广大学员和铁粉的期盼中,终于在公众号发布...
    褚老师TTT阅读 559评论 0 0
  • 小时候一直梦想着去海边。我们的毕业旅行,几个人一起去了三亚。这是第一次看见海。蓝蓝的海蓝蓝的天凉凉的海水嬉闹的游客...
    夙殇阅读 291评论 11 15