热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

iOS讲解迷惑之集成百度地图

cmdshiftN创建一个singel视图,进行各种配置,把任意一个.m文件的后缀名改为.mm1.在appdelegate中#importAppDelegate.h#imp

cmd+shift+N 创建一个 singel视图, 进行各种配置, 把任意一个.m文件的后缀名改为.mm

1. 在appdelegate中

#import "AppDelegate.h"
#import //引入所有的头文件
@interface AppDelegate ()@property (nonatomic, strong) UINavigationController *navC;
@property (nonatomic, strong) BMKMapManager *mapManager;@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {// Override point for customization after application launch._mapManager = [[BMKMapManager alloc]init];// 如果要关注网络及授权验证事件,请设定 generalDelegate参数BOOL ret = [_mapManager start:@"j9UnN8OK0S5EkjY3MPvFxpqc" generalDelegate:nil];if (!ret) {NSLog(@"manager start failed!");}// Add the navigation controller's view to the window and display.[self.window addSubview:_navC.view];return YES;
}


2. 在viewController 

#import "ViewController.h"
#import //引入所有的头文件
#import "UIView+WLFrame.h"
#define kMargin 20
#define kSmallMargin 10// 遵守协议
/**BMKMapViewDelegate 地图协议BMKLocationServiceDelegate 定位服务协议BMKGeoCodeSearchDelegate 地理编码搜索协议BMKRouteSearchDelegate 路线搜索协议*/
@interface ViewController ()
{BOOL _isOpenGPS; // 是否开启定位
}
// 百度的地图类
@property (nonatomic, strong) BMKMapView *mapView;// 定位类 (专门定位)
@property (nonatomic, strong) BMKLocationService *locationService;// 声明地理位置搜索对象 (负责地理坐标编码)
@property (nonatomic, strong) BMKGeoCodeSearch *geoCodeSearch;// 路线搜索类
@property (nonatomic, strong) BMKRouteSearch *routeSearch;///线路检索节点信息,一个路线检索节点可以通过经纬度坐标或城市名加地名确定
// 开始路线检索节点
@property (nonatomic, strong) BMKPlanNode *startNode;// 目标路线检索节点
@property (nonatomic, strong) BMKPlanNode *endNode;@property (nonatomic, strong) UITextField *startCityTF; // 开始城市
@property (nonatomic, strong) UITextField *startAddressTF; // 开始地址
@property (nonatomic, strong) UITextField *endCityTF; // 结束城市
@property (nonatomic, strong) UITextField *endAddressTF; // 结束地址
@end@implementation ViewController置空代理
//- (void)dealloc
//{
// _mapView.delegate = nil;
// _locationService.delegate = nil;
// _geoCodeSearch.delegate = nil;
//}- (void)viewDidLoad {[super viewDidLoad];#pragma mark 地图类_mapView = [[BMKMapView alloc] initWithFrame:[UIScreen mainScreen].bounds];_mapView.delegate = self; // 设置代理[self.view addSubview:_mapView];// 设置地图类型 // 切换卫星地图//[_mapView setMapType:BMKMapTypeSatellite];//打开实时路况图层//[_mapView setTrafficEnabled:YES];// 热力图
// [_mapView setBaiduHeatMapEnabled:YES];// 3D楼块 (默认显示)[_mapView setBuildingsEnabled:YES];// 设置地图跟随位置移动_mapView.userTrackingMode = BMKUserTrackingModeFollow;// 设定显示比例尺_mapView.showMapScaleBar = YES;// 实现BMKMapViewDelegate的_mapView:viewForAnnotation:函数,并在viewDidAppear添加标注数据对象// 添加一个PointAnnotation///表示一个点的annotation
// BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init];
// CLLocationCoordinate2D coor; // 定义结构体 (经纬度)
//
// coor.latitude = 39.915; // 纬度
// coor.longitude = 116.404;
// annotation.coordinate = coor; // 把经纬度赋值给annotation的坐标属性
//
// annotation.title = @"故宫"; // 大头针上面弹出的气泡/***向地图窗口添加标注,需要实现BMKMapViewDelegate的-mapView:viewForAnnotation:函数来生成标注对应的View*@param annotation 要添加的标注*/
// [_mapView addAnnotation:annotation];[self addSubviews];#pragma mark 创建定位服务对象self.locationService = [[BMKLocationService alloc] init];// 设置代理self.locationService.delegate = self;// 设置再次定位的最小距离 (移动超过10米就会再次定位)[BMKLocationService setLocationDistanceFilter:10];//[self.locationService startUserLocationService]; // 1. 开启定位//self.mapView.showsUserLocation = YES; // 2. 在地图上显示用户的信息_isOpenGPS = NO;#pragma mark 创建地理位置搜索对象self.geoCodeSearch = [[BMKGeoCodeSearch alloc] init];self.geoCodeSearch.delegate = self;#pragma mark 创建路线搜索对象self.routeSearch = [[BMKRouteSearch alloc] init];self.routeSearch.delegate = self;}#pragma mark----- 各种控件
- (void)addSubviews
{NSArray *array = @[@"矢量地图", @"卫星地图"];UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:array];segment.frame = CGRectMake((375 - 300) / 2, 25, 300, 30);segment.selectedSegmentIndex = 0; // 默认选中第0个分段segment.backgroundColor = [UIColor colorWithRed:1.000 green:0.146 blue:0.912 alpha:1.000];// 添加方法[segment addTarget:self action:@selector(actionSegment:) forControlEvents:(UIControlEventValueChanged)];[self.view addSubview:segment];UILabel *showHeatLabel = [[UILabel alloc] initWithFrame:CGRectMake(270, 70, 100, 30)];showHeatLabel.text = @"是否显示热力图";showHeatLabel.backgroundColor = [UIColor colorWithRed:1.000 green:0.225 blue:0.904 alpha:1.000];showHeatLabel.font = [UIFont systemFontOfSize:12];[self.view addSubview:showHeatLabel];UISwitch *switchs = [[UISwitch alloc] initWithFrame:CGRectMake(300, 105, 50, 30)];switchs.tintColor = [UIColor colorWithRed:1.000 green:0.186 blue:0.909 alpha:1.000];switchs.onTintColor = [UIColor greenColor];[switchs addTarget:self action:@selector(actionON:) forControlEvents:(UIControlEventTouchUpInside)];[self.view addSubview:switchs];UIButton *openGPSButton = [UIButton buttonWithType:(UIButtonTypeCustom)];openGPSButton.frame = CGRectMake(kMargin, 70,60, 30);openGPSButton.titleLabel.font = [UIFont systemFontOfSize:14];openGPSButton.backgroundColor = [UIColor purpleColor];[openGPSButton setTitle:@"开GPS" forState:(UIControlStateNormal)];[openGPSButton addTarget:self action:@selector(openGPS:) forControlEvents:(UIControlEventTouchUpInside)];[self.view addSubview:openGPSButton];_startCityTF = [[UITextField alloc] initWithFrame:CGRectMake(kMargin, 115, 75, 30)];_startCityTF.text = @"开始城市";_startCityTF.font = [UIFont systemFontOfSize:12];_startCityTF.borderStyle = UITextBorderStyleRoundedRect;[self.view addSubview:_startCityTF];_endCityTF = [[UITextField alloc] initWithFrame:CGRectMake(kMargin, _startCityTF.bottom + kSmallMargin, 75, 30)];_endCityTF.text = @"目的城市";_endCityTF.font = [UIFont systemFontOfSize:12];_endCityTF.borderStyle = UITextBorderStyleRoundedRect;[self.view addSubview:_endCityTF];_startAddressTF = [[UITextField alloc] initWithFrame:CGRectMake(self.startCityTF.right + kMargin + kMargin, 115, 75, 30)];_startAddressTF.text = @"开始地址";_startAddressTF.font = [UIFont systemFontOfSize:12];_startAddressTF.borderStyle = UITextBorderStyleRoundedRect;[self.view addSubview:_startAddressTF];_endAddressTF = [[UITextField alloc] initWithFrame:CGRectMake(self.endCityTF.right + kMargin + kMargin, _startAddressTF.bottom + kSmallMargin, 75, 30)];_endAddressTF.text = @"目的地址";_endAddressTF.font = [UIFont systemFontOfSize:12];_endAddressTF.borderStyle = UITextBorderStyleRoundedRect;[self.view addSubview:_endAddressTF];/**线路规划*/UIButton *searchLineBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];searchLineBtn.frame = CGRectMake(self.startAddressTF.right + kMargin + kMargin, self.startAddressTF.bottom + kSmallMargin, 100, 30);searchLineBtn.backgroundColor = [UIColor colorWithRed:1.000 green:0.197 blue:0.778 alpha:1.000];[searchLineBtn setTitleColor:[UIColor blueColor] forState:(UIControlStateNormal)];[searchLineBtn setTitleColor:[UIColor colorWithRed:0.399 green:0.398 blue:0.461 alpha:1.000] forState:(UIControlStateHighlighted)];[searchLineBtn setTitle:@"线路规划" forState:(UIControlStateNormal)];[searchLineBtn addTarget:self action:@selector(searchLineBtn:) forControlEvents:(UIControlEventTouchUpInside)];[self.view addSubview:searchLineBtn];
}#pragma mark--- 开启 / 关闭 GPS
- (void)openGPS:(UIButton *)btn
{if (_isOpenGPS == NO) {// 打开[self.locationService startUserLocationService]; // 1. 开启定位self.mapView.showsUserLocation = YES; // 2. 在地图上显示用户的信息[btn setTitle:@"关闭GPS" forState:(UIControlStateNormal)];} else {// 1. 关闭定位[self.locationService stopUserLocationService];// 2. 不 在地图上显示用户的信息self.mapView.showsUserLocation = NO;// 3. 删除标识[self.mapView removeAnnotation:[self.mapView.annotations lastObject]];// 如果是关闭状态把按钮标题改为"开启"字样[btn setTitle:@"开启GPS" forState:(UIControlStateNormal)];}_isOpenGPS = !_isOpenGPS;
}// 分段方法
- (void)actionSegment:(UISegmentedControl *)segment
{if (segment.selectedSegmentIndex &#61;&#61; 0) {_mapView.mapType &#61; BMKMapTypeStandard; ///<标准地图} else if (segment.selectedSegmentIndex &#61;&#61; 1) {_mapView.mapType &#61; BMKMapTypeSatellite; // 卫星地图}
}// swith开启关闭方法
- (void)actionON:(UISwitch *)switchs
{if (switchs.isOn &#61;&#61; YES) {// 城市热力图开启_mapView.baiduHeatMapEnabled &#61; YES;} else {_mapView.baiduHeatMapEnabled &#61; NO;}
}#pragma mark---路线规划 按钮方法
- (void)searchLineBtn:(UIButton *)btn
{//NSLog(&#64;"路线");// 完成地理正向编码 (把文字信息变为地理信息)// 1. 创建正向地理编码选项BMKGeoCodeSearchOption *geoSearchOPtion &#61; [[BMKGeoCodeSearchOption alloc] init];// 2. 给想进行正向地理位置编码的位置赋值geoSearchOPtion.city &#61; self.startCityTF.text;geoSearchOPtion.address &#61; self.startAddressTF.text;// 执行地理位置编码[self.geoCodeSearch geoCode:geoSearchOPtion]; // 会触发代理回调方法 BMKGeoCodeSearch的代理方法}#pragma mark----- BMKMapViewDelegate 代理方法 -------------------------
// 设置大头针
// ///大头针的颜色&#xff0c;有BMKPinAnnotationColorRed, BMKPinAnnotationColorGreen, BMKPinAnnotationColorPurple三种
/***根据anntation生成对应的View*&#64;param mapView 地图View*&#64;param annotation 指定的标注*&#64;return 生成的标注View*/
/*
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id)annotation
{// 大头针标注BMKPinAnnotationView *pinView &#61; (BMKPinAnnotationView *)[_mapView dequeueReusableAnnotationViewWithIdentifier:&#64;"大头针标识符"];if (pinView &#61;&#61; nil) {pinView &#61; [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:&#64;"大头针标识符"];}// 设置大头针的颜色pinView.pinColor &#61; BMKPinAnnotationColorPurple;pinView.canShowCallout &#61; YES;return pinView;
}*//***将经纬度坐标转换为View坐标*&#64;param coordinate 待转换的经纬度坐标*&#64;param view 指定相对的View*&#64;return 转换后的View坐标*/
//- (CGPoint)convertCoordinate:(CLLocationCoordinate2D)coordinate toPointToView:(UIView *)view
//{
// CGFloat la &#61; coordinate.latitude;
// CGFloat lon &#61; coordinate.longitude;
// CGPoint point &#61; CGPointMake(la, lon);
//
// return point;
//}/***动态更新我的位置数据* &#64;param [in] userLocation 定位数据*/
//-(void)updateLocationData:(BMKUserLocation*)userLocation
//{NSLog(&#64;"%&#64;");
//}#pragma mark----定位服务类的代理方法 BMKLocationServiceDelegate- (void)willStartLocatingUser
{NSLog(&#64;"开始定位");
}- (void)didFailToLocateUserWithError:(NSError *)error
{NSLog(&#64;"定位失败, 原因: %&#64;", [error description]);
}// 已经更新位置后再次定位成功的方法 (这里面可以插入大头针)
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{NSLog(&#64;"定位成功");// 完成地理反编码// 1.创建反向地理编码选项对象BMKReverseGeoCodeOption *reverseOPtion &#61; [[BMKReverseGeoCodeOption alloc] init];// 2. 给反向地理编码选项对象的坐标点赋值reverseOPtion.reverseGeoPoint &#61; userLocation.location.coordinate;// 3. 执行反向地里编码操作[self.geoCodeSearch reverseGeoCode:reverseOPtion]; // 会触反地理编码代理方法/*//--------- 插入大头针 开始 ------------------------------------------------------// 插入大头针// 定义大头针标注BMKPointAnnotation *annotatiom &#61; [[BMKPointAnnotation alloc] init];// 设置标注的位置坐标annotatiom.coordinate &#61; userLocation.location.coordinate;// 点击大头针弹出气泡annotatiom.title &#61; &#64;"你好";// 把标注添加到地图里面[_mapView addAnnotation:annotatiom];// 使地图显示在该标注的位置[_mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];//--------- 插入大头针 结束 ------------------------------------------------------*/
}#pragma mark-- BMKGeoCodeSearch的代理方法// 反向地理编码成功后的代理方法, 在这里插入大头针, 把大头针的title改为反向编码后的信息
/**反向的地理编码的回调方法*返回反地理编码搜索结果*&#64;param searcher 搜索对象*&#64;param result 搜索结果*&#64;param error 错误号&#xff0c;&#64;see BMKSearchErrorCode*/
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{BMKPointAnnotation *annotatiom &#61; [[BMKPointAnnotation alloc] init];// 设置标注的位置坐标annotatiom.coordinate &#61; result.location;// 点击大头针弹出气泡annotatiom.title &#61; result.address; //地址名称// 把标注添加到地图里面[_mapView addAnnotation:annotatiom];// 使地图显示在该标注的位置[_mapView setCenterCoordinate:result.location animated:YES];
}/**正向地理编码的回调方法*返回地址信息搜索结果*&#64;param searcher 搜索对象*&#64;param result 搜索结BMKGeoCodeSearch果*&#64;param error 错误号&#xff0c;&#64;see BMKSearchErrorCode*/
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{// 判断if ([result.address isEqualToString:_startAddressTF.text]) {// 进入这个判断 说明是当前编码的对象是开始节点self.startNode &#61; [[BMKPlanNode alloc] init];_startNode.pt &#61; result.location; // 给节点的坐标位置赋值// 发起对目标节点地理编码// 1. 创建正向地理编码选项BMKGeoCodeSearchOption *geoOption &#61; [[BMKGeoCodeSearchOption alloc] init];// 赋值geoOption.city &#61; _endCityTF.text;geoOption.address &#61; _endAddressTF.text;// 执行正向编码[self.geoCodeSearch geoCode:geoOption];self.endNode &#61; nil;} else {self.endNode &#61; [[BMKPlanNode alloc] init];_endNode.pt &#61; result.location;}if (_startNode !&#61; nil && _endNode !&#61; nil) {// 开始进行路线规划// 1. 创建驾车路线规划BMKDrivingRoutePlanOption *drivingRoutOP &#61; [[BMKDrivingRoutePlanOption alloc] init];// z指定开始节点 和 目标节点drivingRoutOP.from &#61; _startNode;drivingRoutOP.to &#61; _endNode;// 3. 让路线搜索服务对象搜锁路线[self.routeSearch drivingSearch:drivingRoutOP];}}#pragma mark---- 获取到开车的路线的回调
- (void)onGetDrivingRouteResult:(BMKRouteSearch *)searcher result:(BMKDrivingRouteResult *)result errorCode:(BMKSearchErrorCode)error
{// 删除原来的覆盖物NSArray *array &#61; [NSArray arrayWithObject:_mapView.annotations];[_mapView removeAnnotations:array];array &#61; [NSArray arrayWithArray:_mapView.overlays];[_mapView removeOverlays:array];// //<检索结果正常返回if (error &#61;&#61; BMK_SEARCH_NO_ERROR) {// 选取获取到所有路线中的一条路线BMKDrivingRouteLine *plan &#61; [result.routes objectAtIndex:0];// 计算路线方案中路段的数目 (路段由轨迹点组成)NSUInteger size &#61; [plan.steps count];// 声明一个整形变量原来计算所有轨迹点的总数int planPointCount &#61; 0;for (int i &#61; 0; i )overlay
{if ([overlay isKindOfClass:[BMKPolyline class]]) {// 创建要显示的折现BMKPolylineView *polylineView &#61; [[BMKPolylineView alloc] initWithOverlay:overlay];// 我们设置该线条的填充颜色polylineView.fillColor &#61; [UIColor redColor];// 设置线条的颜色polylineView.strokeColor &#61; [UIColor greenColor];// 设置折现的宽度polylineView.lineWidth &#61; 3.0;return polylineView;}return nil;
}- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.
}&#64;end






推荐阅读
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • 1:有如下一段程序:packagea.b.c;publicclassTest{privatestaticinti0;publicintgetNext(){return ... [详细]
  • 本文详细介绍了如何使用 Yii2 的 GridView 组件在列表页面实现数据的直接编辑功能。通过具体的代码示例和步骤,帮助开发者快速掌握这一实用技巧。 ... [详细]
  • DNN Community 和 Professional 版本的主要差异
    本文详细解析了 DotNetNuke (DNN) 的两种主要版本:Community 和 Professional。通过对比两者的功能和附加组件,帮助用户选择最适合其需求的版本。 ... [详细]
  • 本文详细探讨了JDBC(Java数据库连接)的内部机制,重点分析其作为服务提供者接口(SPI)框架的应用。通过类图和代码示例,展示了JDBC如何注册驱动程序、建立数据库连接以及执行SQL查询的过程。 ... [详细]
  • 本文详细介绍如何在Linux系统中配置SSH密钥对,以实现从一台主机到另一台主机的无密码登录。内容涵盖密钥对生成、公钥分发及权限设置等关键步骤。 ... [详细]
  • 深入解析SpringMVC核心组件:DispatcherServlet的工作原理
    本文详细探讨了SpringMVC的核心组件——DispatcherServlet的运作机制,旨在帮助有一定Java和Spring基础的开发人员理解HTTP请求是如何被映射到Controller并执行的。文章将解答以下问题:1. HTTP请求如何映射到Controller;2. Controller是如何被执行的。 ... [详细]
  • ssm框架整合及工程分层1.先创建一个新的project1.1配置pom.xml ... [详细]
  • 本文详细介绍了 Kubernetes 集群管理工具 kubectl 的基本使用方法,涵盖了一系列常用的命令及其应用场景,旨在帮助初学者快速掌握 kubectl 的基本操作。 ... [详细]
  • Java 架构:深入理解 JDK 动态代理机制
    代理模式是 Java 中常用的设计模式之一,其核心在于代理类与委托类共享相同的接口。代理类主要用于为委托类提供预处理、过滤、转发及后处理等功能,以增强或改变原有功能的行为。 ... [详细]
  • iOS开发之CoreLocation(GPS定位)
    1、概述在iOS开发中,要想加入地图和定位功能这2大功能,必须基于2个框架进行开发(1)MapKit:用于地图 ... [详细]
  • iOS 系统架构 && 常用 framework
    整理自互联网,感谢原文作者!1.iOS基于UNIX系统,因此从系统的稳定性上来说它要比其他操作系统的产品好很多2.iOS的系统架构分为四层,由上到下一次为:可触摸层(CocoaTo ... [详细]
  • L18 如何快速查找文档获得帮助
    原地址:http:www.howzhi.comcourse286lesson2121查找文档快速苹果提供了丰富的文档,以帮助您成功构建和部署你的应用程序, ... [详细]
  • Java项目分层架构设计与实践
    本文探讨了Java项目中应用分层的最佳实践,不仅介绍了常见的三层架构(Controller、Service、DAO),还深入分析了各层的职责划分及优化建议。通过合理的分层设计,可以提高代码的可维护性、扩展性和团队协作效率。 ... [详细]
author-avatar
youdinga
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有