百度地图功能封装

<span style="background-color: rgb(255, 204, 204);">// 功能包括基础地图 定位 线路规划 POI线路检索</span>
<span style="background-color: rgb(255, 204, 204);"><span style="background-color: rgb(255, 204, 204);">//
//  HYBBaiduMapHelper.m
//  BaiduMapDemo
//

#import "HYBBaiduMapHelper.h"

@interface HYBBaiduMapHelper () <BMKLocationServiceDelegate,
BMKGeneralDelegate,
BMKMapViewDelegate,
BMKRouteSearchDelegate> {
  BMKMapManager             *_mapManager;
  HYBUserLocationCompletion _locationCompletion;
  HYBRouteSearchCompletion  _routeSearchCompletion;
  BMKMapView                *_mapView;
  BMKLocationService        *_locationService;
  BMKRouteSearch            *_routeSearch;
}

@end

@implementation HYBBaiduMapHelper

+ (HYBBaiduMapHelper *)shared {
  static HYBBaiduMapHelper *baiduMapHelper = nil;
  static dispatch_once_t onceToken = 0;

  dispatch_once(&onceToken, ^{
    if (!baiduMapHelper) {
      baiduMapHelper = [[[self class] alloc] init];
    }
  });

  return baiduMapHelper;
}

- (instancetype)init {
  if (self = [super init]) {
    _mapManager = [[BMKMapManager alloc] init];
  }

  return self;
}

- (BOOL)startWithAppKey:(NSString *)appKey {
  if (![appKey isKindOfClass:[NSString class]] || appKey.length == 0 || appKey == nil) {
    return NO;
  }

  return [_mapManager start:appKey generalDelegate:self];
}

- (void)locateInView:(UIView *)mapSuerView frame:(CGRect)frame withCompletion:(HYBUserLocationCompletion)completion {
  _locationCompletion = [completion copy];

  [_locationService stopUserLocationService];
  _locationService = nil;
  _locationService.delegate = nil;
  _locationService = [[BMKLocationService alloc] init];
  [_locationService startUserLocationService];

  if (_mapView) {
    [_mapView removeFromSuperview];
    _mapView = nil;
  }
  _mapView.delegate = nil;
  _mapView.showsUserLocation = NO;
  _mapView = [[BMKMapView alloc] initWithFrame:frame];
  [mapSuerView addSubview:_mapView];

  _mapView.delegate = self;
  // 先关闭显示的定位图层
  _mapView.showsUserLocation = NO;
  // 设置定位的状态

  _mapView.userTrackingMode = BMKUserTrackingModeNone;
  _mapView.showsUserLocation = YES;
  return;
}

- (void)viewWillAppear {
  [_mapView viewWillAppear];

  _mapView.delegate = self;
  _locationService.delegate = self;
  _routeSearch.delegate = self;
  return;
}

- (void)viewWillDisappear {
  [_mapView viewWillDisappear];

  _mapView.delegate = nil;
  _locationService.delegate = nil;
  _routeSearch.delegate = nil;
  return;
}

- (void)viewDidDeallocOrReceiveMemoryWarning {
  [self viewWillDisappear];

  _mapView.showsUserLocation = NO;
  [_locationService stopUserLocationService];
  [_mapView removeFromSuperview];
  _mapView = nil;

  _locationService = nil;
  _routeSearch.delegate = nil;
  _routeSearch = nil;
  return;
}

///
/// 计算两点的距离
- (CLLocationDistance)distanceWithStartPoint:(CLLocationCoordinate2D)startPoint endPoint:(CLLocationCoordinate2D)endPoint {
  BMKMapPoint point1 = BMKMapPointForCoordinate(startPoint);
  BMKMapPoint point2 = BMKMapPointForCoordinate(endPoint);
  CLLocationDistance distance = BMKMetersBetweenMapPoints(point1, point2);
  return distance;
}

///
/// 下面的方法是路线规划获取操作
/// 公交检索方法
/// 前两个参数,分别表示起点和终点的位置名称
/// 第三个参数,表示在哪个城市里检索
- (void)transitRouteSearchFrom:(BMKPlanNode *)startNode
                            to:(BMKPlanNode *)endNode
                          city:(NSString *)city
                 transitPolicy:(BMKTransitPolicy)transitPolicy
                    completion:(HYBRouteSearchCompletion)completion {
  _routeSearchCompletion = [completion copy];

  if (_routeSearch == nil) {
    _routeSearch = [[BMKRouteSearch alloc] init];
  }

  _routeSearch.delegate = self;

  // 公交检索
  BMKTransitRoutePlanOption *transitRoutePlan = [[BMKTransitRoutePlanOption alloc] init];
  transitRoutePlan.city = city;
  transitRoutePlan.from = startNode;
  transitRoutePlan.to = endNode;
  transitRoutePlan.transitPolicy = transitPolicy;

  if ([_routeSearch transitSearch:transitRoutePlan]) {
    NSLog(@"bus检索发送成功");
  } else {
    NSLog(@"bus检索发送失败");
  }
  return;
}

/// 驾乘检索方法
/// 前两个参数,分别表示起点和终点的位置名称
- (void)driveRouteSearchFrom:(BMKPlanNode *)startNode
                          to:(BMKPlanNode *)endNode
                 drivePolicy:(BMKDrivingPolicy)drivePolicy
                  completion:(HYBRouteSearchCompletion)completion {
  _routeSearchCompletion = [completion copy];

  if (_routeSearch == nil) {
    _routeSearch = [[BMKRouteSearch alloc] init];
  }

  _routeSearch.delegate = self;

  // 公交检索
  BMKDrivingRoutePlanOption *driveRoutePlan = [[BMKDrivingRoutePlanOption alloc] init];
  driveRoutePlan.from = startNode;
  driveRoutePlan.to = endNode;
  driveRoutePlan.drivingPolicy = drivePolicy;

  if ([_routeSearch drivingSearch:driveRoutePlan]) {
    NSLog(@"drive 检索发送成功");
  } else {
    NSLog(@"drive 检索发送失败");
  }
  return;
}

/// 步行检索方法
/// 前两个参数,分别表示起点和终点的位置名称
- (void)walkRouteSearchFrom:(BMKPlanNode *)startNode
                         to:(BMKPlanNode *)endNode
                 completion:(HYBRouteSearchCompletion)completion {
  _routeSearchCompletion = [completion copy];

  if (_routeSearch == nil) {
    _routeSearch = [[BMKRouteSearch alloc] init];
  }

  _routeSearch.delegate = self;

  // 公交检索
  BMKWalkingRoutePlanOption *walkRoutePlan = [[BMKWalkingRoutePlanOption alloc] init];
  walkRoutePlan.from = startNode;
  walkRoutePlan.to = endNode;

  if ([_routeSearch walkingSearch:walkRoutePlan]) {
    NSLog(@"walk 检索发送成功");
  } else {
    NSLog(@"walk 检索发送失败");
  }
  return;
}

#pragma mark - BMKGeneralDelegate
- (void)onGetNetworkState:(int)iError {
  if (0 == iError) {
    NSLog(@"联网成功");
  } else {
    NSLog(@"onGetNetworkState %d",iError);
  }
  return;
}

- (void)onGetPermissionState:(int)iError {
  if (0 == iError) {
    NSLog(@"百度地图授权成功");
  } else {
    NSLog(@"onGetPermissionState %d",iError);
  }
  return;
}

#pragma mark - BMKLocationServiceDelegate
/**
 *在将要启动定位时,会调用此函数
 */
- (void)willStartLocatingUser {
  NSLog(@"location start");
  return;
}

/**
 *在停止定位后,会调用此函数
 */
- (void)didStopLocatingUser {
  NSLog(@"user location stop");
  return;
}

/**
 *用户方向更新后,会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation {
  NSLog(@"user derection change");
  [_mapView updateLocationData:userLocation];
  return;
}

/**
 *用户位置更新后,会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserLocation:(BMKUserLocation *)userLocation {
  NSLog(@"didUpdateUserLocation lat %f,long %f",
        userLocation.location.coordinate.latitude,
        userLocation.location.coordinate.longitude);
  [_mapView updateLocationData:userLocation];
  if (_locationCompletion) {
    _locationCompletion(userLocation);
  }

  [_locationService stopUserLocationService];
  return;
}

/**
 *定位失败后,会调用此函数
 *@param error 错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error {
  if (_locationCompletion) {
    _locationCompletion(nil);
  }

  [_locationService stopUserLocationService];
  return;
}

#pragma mark - BMKRouteSearchDelegate
- (void)onGetTransitRouteResult:(BMKRouteSearch *)searcher
                         result:(BMKTransitRouteResult *)result
                      errorCode:(BMKSearchErrorCode)error {
  if (error == BMK_SEARCH_NO_ERROR) { // 检索成功的处理
    for (BMKTransitRouteLine *line in result.routes) {
      NSLog(@"-----------------------------------------------------");
      NSLog(@"  时间:%2d %2d:%2d:%2d 长度: %d米",
            line.duration.dates,
            line.duration.hours,
            line.duration.minutes,
            line.duration.seconds,
            line.distance);
      for (BMKTransitStep *step in line.steps) {
        NSLog(@"%@     %@    %@    %@    %@",
              step.entrace.title,
              step.exit.title,
              step.instruction,
              (step.stepType == BMK_BUSLINE ? @"公交路段" : (step.stepType == BMK_SUBWAY ? @"地铁路段" : @"步行路段")),
              [NSString stringWithFormat:@"名称:%@  所乘站数:%d   全程价格:%d  区间价格:%d",
               step.vehicleInfo.title,
               step.vehicleInfo.passStationNum,
               step.vehicleInfo.totalPrice,
               step.vehicleInfo.zonePrice]);
      }
    }

    // 打车信息
    NSLog(@"打车信息------------------------------------------");
    NSLog(@"路线打车描述信息:%@  总路程: %d米    总耗时:约%f分钟  每千米单价:%f元  全程总价:约%d元",
          result.taxiInfo.desc,
          result.taxiInfo.distance,
          result.taxiInfo.duration / 60.0,
          result.taxiInfo.perKMPrice,
          result.taxiInfo.totalPrice);

  } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR) { // 检索地址有岐义,可获取推荐地址
    // 获取建议检索起终点
    NSLog(@"无检索结果,返回了建议检索信息");

    NSLog(@"起点推荐信息:--------------------------------");
    for (BMKPoiInfo *info in result.suggestAddrResult.startPoiList) {
      NSLog(@"POI名称:%@     POI地址:%@     POI所在城市:%@", info.name, info.address, info.city);
    }

    NSLog(@"终点推荐信息:--------------------------------");
    for (BMKPoiInfo *info in result.suggestAddrResult.endPoiList) {
      NSLog(@"POI名称:%@     POI地址:%@     POI所在城市:%@", info.name, info.address, info.city);
    }
  } else {
    NSLog(@"无公交检索结果 ");
  }

  // 回调block根据实际需要返回,可修改返回结构
  if (_routeSearchCompletion) {
    _routeSearchCompletion(nil); // 这里只是返回空,这个需要根据实际需要返回
  }
  return;
}

- (void)onGetDrivingRouteResult:(BMKRouteSearch *)searcher
                         result:(BMKDrivingRouteResult *)result
                      errorCode:(BMKSearchErrorCode)error {
  if (error == BMK_SEARCH_NO_ERROR) { // 检索成功的处理
    for (BMKDrivingRouteLine *line in result.routes) {
      NSLog(@"-----------------------------------------------------");
      NSLog(@"  时间:%2d %2d:%2d:%2d 长度: %d米",
            line.duration.dates,
            line.duration.hours,
            line.duration.minutes,
            line.duration.seconds,
            line.distance);
      for (BMKDrivingStep *step in line.steps) {
        NSLog(@"入口:%@   出口:%@   路段总体指示信息:%@    入口信息:%@    出口信息:%@  转弯数:%d",
              step.entrace.title,
              step.exit.title,
              step.instruction,
              step.entraceInstruction,
              step.exitInstruction,
              step.numTurns);
      }
    }
  } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR) { // 检索地址有岐义,可获取推荐地址
    // 获取建议检索起终点
    NSLog(@"无检索结果,返回了建议检索信息");

    NSLog(@"起点推荐信息:--------------------------------");
    for (BMKPoiInfo *info in result.suggestAddrResult.startPoiList) {
      NSLog(@"POI名称:%@     POI地址:%@     POI所在城市:%@", info.name, info.address, info.city);
    }

    NSLog(@"终点推荐信息:--------------------------------");
    for (BMKPoiInfo *info in result.suggestAddrResult.endPoiList) {
      NSLog(@"POI名称:%@     POI地址:%@     POI所在城市:%@", info.name, info.address, info.city);
    }
  } else {
    NSLog(@"无公交检索结果 ");
  }

  // 回调block根据实际需要返回,可修改返回结构
  if (_routeSearchCompletion) {
    _routeSearchCompletion(nil); // 这里只是返回空,这个需要根据实际需要返回
  }
  return;
}

- (void)onGetWalkingRouteResult:(BMKRouteSearch *)searcher
                         result:(BMKWalkingRouteResult *)result
                      errorCode:(BMKSearchErrorCode)error {
  if (error == BMK_SEARCH_NO_ERROR) { // 检索成功的处理
    for (BMKDrivingRouteLine *line in result.routes) {
      NSLog(@"步行检索结果 :-----------------------------------------------------");
      NSLog(@"  时间:%2d %2d:%2d:%2d 长度: %d米",
            line.duration.dates,
            line.duration.hours,
            line.duration.minutes,
            line.duration.seconds,
            line.distance);
      for (BMKWalkingStep *step in line.steps) {
        NSLog(@"入口:%@   出口:%@   路段总体指示信息:%@    入口信息:%@    出口信息:%@",
              step.entrace.title,
              step.exit.title,
              step.instruction,
              step.entraceInstruction,
              step.exitInstruction);
      }
    }
  } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR) { // 检索地址有岐义,可获取推荐地址
    // 获取建议检索起终点
    NSLog(@"无检索结果,返回了建议检索信息");

    NSLog(@"起点推荐信息:--------------------------------");
    for (BMKPoiInfo *info in result.suggestAddrResult.startPoiList) {
      NSLog(@"POI名称:%@     POI地址:%@     POI所在城市:%@", info.name, info.address, info.city);
    }

    NSLog(@"终点推荐信息:--------------------------------");
    for (BMKPoiInfo *info in result.suggestAddrResult.endPoiList) {
      NSLog(@"POI名称:%@     POI地址:%@     POI所在城市:%@", info.name, info.address, info.city);
    }
  } else {
    NSLog(@"无公交检索结果 ");
  }

  // 回调block根据实际需要返回,可修改返回结构
  if (_routeSearchCompletion) {
    _routeSearchCompletion(nil); // 这里只是返回空,这个需要根据实际需要返回
  }
  return;
}

@end

//
//  RootViewController.m
//  BaiduMapDemo

#import "RootViewController.h"
#import "HYBBaiduMapHelper.h"
#import "BMapKit.h"

@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // 功能1、定位
  [[HYBBaiduMapHelper shared] locateInView:self.view frame:self.view.bounds withCompletion:^(BMKUserLocation *userLocation) {
    NSLog(@"%f  %f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
  }];

  // 功能2:”计算距离
 CLLocationDistance distance = [[HYBBaiduMapHelper shared] distanceWithStartPoint:CLLocationCoordinate2DMake(39.915,116.404)
                                            endPoint:CLLocationCoordinate2DMake(38.915,115.404)];
  NSLog(@"distance = %fm", distance);

  // 功能3:公交检索
  BMKPlanNode *startNode = [[BMKPlanNode alloc] init];
  startNode.name = @"梆子井";
  startNode.cityName = @"北京";

  BMKPlanNode *endNode = [[BMKPlanNode alloc] init];
  endNode.name = @"金长安大厦";
  endNode.cityName = @"北京";

  // 功能3:公交检索
  [[HYBBaiduMapHelper shared] transitRouteSearchFrom:startNode to:endNode city:@"北京" transitPolicy:BMK_TRANSIT_TRANSFER_FIRST completion:^(BMKTransitRouteResult *result) {
    // 功能4:驾乘检索
    [[HYBBaiduMapHelper shared] driveRouteSearchFrom:startNode to:endNode drivePolicy:BMK_DRIVING_TIME_FIRST  completion:^(BMKTransitRouteResult *result) {
      // 功能5:步行检索
      [[HYBBaiduMapHelper shared] walkRouteSearchFrom:startNode to:endNode completion:^(BMKTransitRouteResult *result) {
        ;
      }];
    }];
  }];
  return;
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];

  [[HYBBaiduMapHelper shared] viewWillAppear];

  return;
}

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];

  [[HYBBaiduMapHelper shared] viewWillDisappear];
  return;
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];

  [[HYBBaiduMapHelper shared] viewDidDeallocOrReceiveMemoryWarning];
  return;
}

- (void)dealloc {
  [[HYBBaiduMapHelper shared] viewDidDeallocOrReceiveMemoryWarning];
  return;
}
@end
</span></span>

时间: 2024-10-31 22:22:42

百度地图功能封装的相关文章

Vue项目引用百度地图并实现搜索定位等功能

Tip:本篇文章为案例分析,技术点较多,所以篇幅较长,认真阅览的你一定会学到很多知识. 前言:百度地图开放平台 给开发者们提供了丰富的地图功能与服务,使我们的项目中可以轻松地实现地图定位.地址搜索.路线导航等功能.本文给大家介绍如何在vue项目中引用百度地图,并设计实现简单的地图定位.地址搜索功能. 一.效果图及功能点 先来看一下效果图 效果图看不够? 点此 试试在线操作!(初次进入加载较慢,请耐心等待) 功能点: 挂载百度地图 封装逆地址解析函数(根据坐标点获取详细地址) 设置图像标注并绑定拖

开发百度地图之实现

在地图上标记用户当前所处位置其实是一个GPS定位应用.首先通过GPS定位获取到用户当前所在位置的经纬度,再将该经纬度所代表的点在地图上标出来.其实除了在地图上标注自己所处的位置外,我们通常还有这样的需求:“如果我的位置发生改变,要能够实时在地图上体现出来”. 新建项目baidumaplocation.设计main.xml文件这里注意的是MapView控件必须使用来自百度库封装好的com.baidu.mapapi.MapView .设计代码如下: Xml代码 [url=] [/url] 1.<?x

百度地图LBS应用开发代码

最近因为工作需要,领导要我将51地图API开发的一个应用迁移到百度地图,或者说用百度地图API进行重写,实现同样的功能.我先是把现有的这个51地图的应用了解了一下,然后就试着用百度地图做一些demo,最后就自己动手参照原来的应用的功能,用百度地图实现了一下.下面就给大家介绍一下,百度地图API开发的一些基础技术. 首先,百度地图API的官方首页是:http://dev.baidu.com/wiki/static/index.htm,上面介绍了很多详细的信息,各种版本的API,成功案例,还有在线帮

android 百度地图系列之地图初始化及定位

在Android应用中,很多时候需要地图功能,回顾过去写的项目和百度地图api,开始总结一下Android百度地图的实现.首先总结一下怎么开始一个Android百度地图功能. 当使用百度地图的时候,提到一个appkey."在使用百度地图SDK为您提供的各种LBS能力之前,您需要获取百度地图移动版的开发密钥,该密钥与您的百度账户相关联.因此,您必须先有百度帐户,才能获得开发密钥.并且,该密钥与您创建的过程名称有关.Key地址为:http://lbsyun.baidu.com/apiconsole/

百度地图 IOS版开发经验分享

最近刚完成app中地图的应用,感觉非常的曲折,折腾了很久,刚才开始一直不能成功使用百度地图api,报一大堆的错误,后来换到高德地图,又发现服务端使用的百度的经纬度,又从高德换回百度,泪奔. 这里简单比较下高德地图和百度地图,个人觉得高德地图api导入真是非常简单,而且还分成几种版本:相比较百度地图api的导入就繁琐多了,主要是导入静态库文件,初次使用真的是繁琐,百度提供了三种导入方式,最后还是觉得合并静态库文件比较方便,不然要在xcode中作很多设置,而且还要根据各种情况更改,所以我建议还是选择

android,百度地图只见网格不见图层

在android开发中,使用百度地图功能,出现了只见网格不见图层的问题,经过一番查找,才得出是由于自己错误的使用了apk自己的sha1值来申请key才导致这样的问题. 在申请key时,需要使用eclipse中android下build的sha1值.这样就正常了. android,百度地图只见网格不见图层

android 基于百度地图api开发定位以及获取详细地址

一:百度地图开发必须要到百度开发平台android开发api下载相应的库,已经申请百度地图开发key. 二:新建项目baidumaplocation.设计main.xml文件这里注意的是MapView控件必须使用来自百度库封装好的com.baidu.mapapi.MapView .设计代码如下: Xml代码   <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&q

App解读

一直不懂别人口中说的原生开发.混合式开发.今天突然看了一篇文章讲解的是什么叫做原生App?移动 Web App?混合APP?分享给大家. 原生App是专门针对某一类移动设备而生的,它们都是直接安装到设备里,而用户一般也是通过网络商店或者卖场来获取例如 The App Store与Android Apps on Google Play. 什么叫移动 Web App? 一般来说,移动 Web App都是需要用到网络的,它们利用设备上的浏览器来运行,而且它们不需要在设备上下载后安装. 什么是混合App

Hybrid APP介绍

"云"时代的来临正在改变App和运营团队之间的关系,一场不能避免的变革正在进行.鉴于移动终端的局限性,移动终端上的APP由本地化应用(Native App),到混合型应用(Hybrid APP),再到基于WEB的应用Web App,这一连串的变化都源于技术的更新和市场的需要[1] . Hybrid App是指介于web-app.native-app这两者之间的app,它虽然看上去是一个Native App,但只有一个UI WebView,里面访问的是一个Web App,比如街旁网最开始