1. 程式人生 > >iOS 百度地圖的檢索(正向、反向、周邊)

iOS 百度地圖的檢索(正向、反向、周邊)

正向反向檢索:

這裡寫圖片描述

功能描述:
(1)我們在專案中往往會需要根據經緯度在地圖中定位一個地點,在哪裡插個大頭針展示下;
(2)當經緯度沒有的時候,可以根據具體的地址資訊去獲取經緯度在地圖上插個大頭針展示下。

具體的工程:
(1)根據官方文件匯入百度地圖的FrameWork,根據官方文件先處理好所有需要的配置。
(2)我這裡給出的我的程式碼其實在百度的Demo中是可以找到的,我這裡只是總結下我的步驟;

程式碼:

(1)需要的代理:BMKLocationServiceDelegate、BMKMapViewDelegate、BMKGeoCodeSearchDelegate
(2)宣告的成本變數、屬性

BMKLocationService * _locService;
BMKGeoCodeSearch* _geocodesearch;

因為介面使用了xib所以就直接在xib上使用了MapView

@property (strong, nonatomic) IBOutlet BMKMapView *baiduMapView;
- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    //注意這裡需要在這裡重新設定delegate
    self.backScrollView.delegate
= self; //這個方法去除了導航下面的線、這個方法是一個比較好的移除導航條下面的一個線的方法 [self.navigationController.navigationBar setShadowImage:[UIImage new]]; [_baiduMapView viewWillAppear]; _baiduMapView.delegate = self; _locService.delegate = self; _geocodesearch.delegate = self; } - (void)viewDidLoad { [super
viewDidLoad]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; //這裡一定要把Scrollview的代理設定為nil否則會影響到下一個介面的導航 self.backScrollView.delegate = nil; [self.navigationController.navigationBar lt_reset]; [_baiduMapView viewWillDisappear]; // 此處記得不用的時候需要置nil,否則影響記憶體的釋放 _baiduMapView.delegate = nil; _locService.delegate = nil; _geocodesearch.delegate = nil; } - (void)dealloc{ if(_geocodesearch != nil){ _geocodesearch = nil; } if(_baiduMapView){ _baiduMapView = nil; } } - (void)initUI{ _locService = [[BMKLocationService alloc]init]; _geocodesearch = [[BMKGeoCodeSearch alloc]init]; _locService.delegate = self; _baiduMapView.delegate = self; [_locService startUserLocationService]; _baiduMapView.zoomLevel = 14; [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]]; [self createNavButton]; [self refreshView]; } //重新整理介面 - (void)refreshView{ //這裡可以把這個延遲去掉不要 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ // 2秒後非同步執行這裡的程式碼... if(self.createHouseModel.latitude.integerValue == 0){ // //如果檢索失敗就應該讓檢視周邊的按鈕不可點選,箭頭也隱藏掉 BMKGeoCodeSearchOption *geocodeSearchOption = [[BMKGeoCodeSearchOption alloc]init]; if([self.createHouseModel.address rangeOfString:@"市"].location != NSNotFound){ NSArray * array = [self.createHouseModel.address componentsSeparatedByString:@"市"]; geocodeSearchOption.city =array[0]; }else{ geocodeSearchOption.city= @""; } geocodeSearchOption.address = self.createHouseModel.address; BOOL flag = [_geocodesearch geoCode:geocodeSearchOption]; if(flag) { NSLog(@"geo檢索傳送成功"); } else { NSLog(@"geo檢索傳送失敗"); } } else{ CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0}; pt = (CLLocationCoordinate2D){[self.createHouseModel.latitude floatValue], [self.createHouseModel.longitude floatValue]}; BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init]; reverseGeocodeSearchOption.reverseGeoPoint = pt; BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption]; if(flag) { NSLog(@"反geo檢索傳送成功"); } else { NSLog(@"反geo檢索傳送失敗"); } } }); } //根據anntation生成對應的View - (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{ NSString *AnnotationViewID = @"annotationViewID"; //根據指定標識查詢一個可被複用的標註View,一般在delegate中使用,用此函式來代替新申請一個View BMKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID]; if (annotationView == nil) { annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID]; ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed; ((BMKPinAnnotationView*)annotationView).animatesDrop = YES; } annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5)); annotationView.annotation = annotation; annotationView.canShowCallout = YES; return annotationView; } - (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error { NSArray* array = [NSArray arrayWithArray:_baiduMapView.annotations]; [_baiduMapView removeAnnotations:array]; array = [NSArray arrayWithArray:_baiduMapView.overlays]; [_baiduMapView removeOverlays:array]; if (error == 0) { self.locationFailRemarkView.hidden = YES; BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init]; item.coordinate = result.location; item.title = self.createHouseModel.esidentialquarters;//標題是小區的名稱; [_baiduMapView addAnnotation:item]; _baiduMapView.centerCoordinate = result.location; self.createHouseModel.latitude = [NSString stringWithFormat:@"%f",item.coordinate.latitude]; self.createHouseModel.longitude = [NSString stringWithFormat:@"%f",item.coordinate.longitude]; }else{ self.locationFailRemarkView.hidden = NO; } } -(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error { NSArray* array = [NSArray arrayWithArray:_baiduMapView.annotations]; [_baiduMapView removeAnnotations:array]; array = [NSArray arrayWithArray:_baiduMapView.overlays]; [_baiduMapView removeOverlays:array]; if (error == 0) { self.locationFailRemarkView.hidden = YES; BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init]; item.coordinate = result.location; item.title = self.createHouseModel.esidentialquarters;//標題是小區的名稱; [_baiduMapView addAnnotation:item]; _baiduMapView.centerCoordinate = result.location; }else{ self.locationFailRemarkView.hidden = NO; } } //代理方法 - (void)didUpdateUserHeading:(BMKUserLocation *)userLocation{ [_baiduMapView updateLocationData:userLocation]; } - (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{ [_baiduMapView updateLocationData:userLocation]; }

周邊檢索

這裡寫圖片描述

這裡的檢索程式碼在百度的Demo中也是可以找到的。這裡我做了一點點的修改。不過還存在一個問題,當點選搜尋“地鐵”的時候無法出現

#import "NeighbourViewController.h"
#import "SliderView.h"

@interface NeighbourViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,SliderViewDelegate,BMKPoiSearchDelegate>{

    NSString * searchSign;

     BMKLocationService * _locService;
     BMKPoiSearch* _poisearch;
}

@property (nonatomic,strong) BMKMapView * baiduMapView;
@property (nonatomic,strong) SliderView * sliderView;
@property (nonatomic,strong) UIButton * rightButton;

@end

@implementation NeighbourViewController


- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    [self.baiduMapView viewWillAppear];
    self.baiduMapView.delegate = self; // 此處記得不用的時候需要置nil,否則影響記憶體的釋放
    _locService.delegate = self;
    _poisearch.delegate = self;


}

- (void)viewDidLoad {
    [super viewDidLoad];
    _poisearch = [[BMKPoiSearch alloc]init];
    _locService = [[BMKLocationService alloc]init];
    [_locService startUserLocationService];

    self.view.backgroundColor = [UIColor whiteColor];

}

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];

    [self.baiduMapView viewWillDisappear];
    _poisearch.delegate = nil; // 不用時,置nil
    self.baiduMapView.delegate = nil; // 不用時,置nil
    _locService.delegate = nil;
}

- (void)initData{

}

- (void)initUI{

    [self createRightButton];


    [self goBackBtn];
    [self createBaiduMapView];
    [self createBottomView];

    [self startLocation];//開始定位

}

- (void)createRightButton{

    self.rightButton = [self createRightItemAction:@selector(rightButtonClick:)];
    [self.rightButton setTitle:@"導航" forState:UIControlStateNormal];

    self.rightButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];

    self.rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    self.rightButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -10);


}

//導航按鈕的點選
- (void)rightButtonClick:(UIButton *)button{

    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://map/"]])
    {

        double m_wd = _locService.userLocation.location.coordinate.latitude;
        double m_jd = _locService.userLocation.location.coordinate.longitude;

        NSString *urlString = [NSString stringWithFormat:@"baidumap://map/direction?origin=%f,%f&destination=%f,%f&mode=driving&src=webapp.navi.yourCompanyName.yourAppName",m_wd,m_jd,self.latFloat,self.logFloat];

        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];
    }else{
        [SVProgressHUD showErrorWithStatus:@"您沒有安裝百度地圖,無法為你導航"];
    }
}


- (void)createBaiduMapView{

    self.baiduMapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 50)];

    // 設定地圖級別
    [self.baiduMapView setZoomLevel:13];

    [self.view addSubview:self.baiduMapView];
}

- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation{
    [self.baiduMapView updateLocationData:userLocation];
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    [self.baiduMapView updateLocationData:userLocation];

}

#pragma mark 開始定位

- (void)startLocation{

    CLLocationCoordinate2D coordinate;
    coordinate.latitude = self.latFloat;
    coordinate.longitude = self.logFloat;
    [_locService startUserLocationService];
    self.baiduMapView.userTrackingMode = BMKUserTrackingModeNone;//設定定位的狀態
    [self.baiduMapView setShowsUserLocation:YES];

    BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
    annotation.coordinate = coordinate;
    annotation.title = self.titleStr;
    [self.baiduMapView addAnnotation:annotation];


    self.baiduMapView.centerCoordinate = coordinate;
}

- (void)createBottomView{

    NSMutableArray * titleArray = [[NSMutableArray alloc]initWithObjects:@"銀行",@"公交",@"地鐵",@"教育",@"醫院",@"休閒",@"購物",@"健身",@"美食",nil];

    self.sliderView = [[SliderView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 50, SCREEN_WIDTH, 50) titleArray:titleArray];

    self.sliderView.sliderDelegate = self;
    [self.view addSubview:self.sliderView];


}

- (void)itemButtonClick:(UIButton *)button{


    NSString * searchTitle = button.titleLabel.text;
    searchSign = searchTitle;

    BMKNearbySearchOption * nearSearch = [[BMKNearbySearchOption alloc]init];
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = self.latFloat;
    coordinate.longitude = self.logFloat;
    nearSearch.pageIndex = 1;
    nearSearch.pageCapacity = 20;
    nearSearch.location = coordinate;
    nearSearch.radius = 3000;
    nearSearch.keyword = searchTitle;
    BOOL flag = [_poisearch poiSearchNearBy:nearSearch];
    if(flag)
    {

        NSLog(@"城市內檢索傳送成功");
    }
    else
    {

        NSLog(@"城市內檢索傳送失敗");
    }

}

- (void)dealloc {
    if (_poisearch != nil) {
        _poisearch = nil;
    }
    if (_baiduMapView) {
        _baiduMapView = nil;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/**
 *根據anntation生成對應的View
 *@param mapView 地圖View
 *@param annotation 指定的標註
 *@return 生成的標註View
 */
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{  
    NSString *AnnotationViewID = @"xidanMark";

    BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];

    // 快取沒有命中,自己構造一個,一般首次新增annotation程式碼會執行到此處
    if (newAnnotationView == nil) {

        newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)newAnnotationView).pinColor = BMKPinAnnotationColorRed;
        // 設定重天上掉下的效果(annotation)
        ((BMKPinAnnotationView*)newAnnotationView).animatesDrop = YES;
    }


    newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
    newAnnotationView.animatesDrop = YES;// 設定該標註點動畫顯示
    newAnnotationView.annotation=annotation;


    if([searchSign isEqualToString:@"銀行"]){
       newAnnotationView.image = [UIImage imageNamed:@"location_bank"];

    }else if([searchSign isEqualToString:@"公交"]){

       newAnnotationView.image = [UIImage imageNamed:@"location_transit"];

    }else if([searchSign isEqualToString:@"銀行"]){
        newAnnotationView.image = [UIImage imageNamed:@"location_bank"];
    }else if([searchSign isEqualToString:@"地鐵"]){
        newAnnotationView.image = [UIImage imageNamed:@"location_subWay"];
    }else if([searchSign isEqualToString:@"教育"]){
        newAnnotationView.image = [UIImage imageNamed:@"location_eductation"];
    }else if([searchSign isEqualToString:@"醫院"]){
        newAnnotationView.image = [UIImage imageNamed:@"location_hospital"];
    }else if([searchSign isEqualToString:@"休閒"]){
        newAnnotationView.image = [UIImage imageNamed:@"location_casual"];
    }else if([searchSign isEqualToString:@"購物"]){
        newAnnotationView.image = [UIImage imageNamed:@"location_shopping"];
    }else if([searchSign isEqualToString:@"健身"]){
        newAnnotationView.image = [UIImage imageNamed:@"location_physical"];
    }else if([searchSign isEqualToString:@"美食"]){
        newAnnotationView.image = [UIImage imageNamed:@"location_food"];
    }

//    newAnnotationView.image = [UIImage imageNamed:@"home_push.jpg"];   //把大頭針換成別的圖片
    newAnnotationView.size = CGSizeMake(28, 35);
    return newAnnotationView;

}
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    [mapView bringSubviewToFront:view];
    [mapView setNeedsDisplay];
}
- (void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    NSLog(@"didAddAnnotationViews");
}

#pragma mark -
#pragma mark implement BMKSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error
{
    [SVProgressHUD show];
    // 清楚螢幕中所有的annotation
    NSMutableArray* array = [NSMutableArray arrayWithArray:_baiduMapView.annotations];
    for(int i = 0; i < array.count; i++){

        BMKPointAnnotation * annotation = array[i];
        if([annotation.title isEqualToString:self.titleStr]){
            [array removeObject:annotation];
        }
    }
    [_baiduMapView removeAnnotations:array];

    if (error == BMK_SEARCH_NO_ERROR) {

        NSMutableArray *annotations = [NSMutableArray array];
        for (int i = 0; i < result.poiInfoList.count; i++) {

            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
            item.coordinate = poi.pt;
            item.title = poi.name;
            [annotations addObject:item];
        }
        [_baiduMapView addAnnotations:annotations];
        [_baiduMapView showAnnotations:annotations animated:YES];


    } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
        NSLog(@"起始點有歧義");
    } else {
        // 各種情況的判斷。。。
    }

    [SVProgressHUD dismiss];
}

@end