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 ()
{
    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)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(@"点击泡泡");
}

你可能感兴趣的:(iOS调用百度地图踩坑(一))