集成百度地图过程不做讲解,直接按照官方文档一步步走即可 开发指南
效果图
- 引入头文件
#import <MapKit/MapKit.h>
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件
#import <BaiduMapAPI_Map/BMKMapView.h>//只引入所需的单个头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
- 创建地图和定位功能
//进入普通定位态
self.locService = [[BMKLocationService alloc]init];
[self.locService startUserLocationService];
// 定位的精读 例如100米的位置 以内就算定位出你的位置 值越小越耗电
// self.locService.desiredAccuracy = 100;
// 设置当超过设定距离的时候 开启定位
self.locService.distanceFilter = 100;
self.mapView.showsUserLocation = NO;//先关闭显示的定位图层
self.mapView.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态
self.mapView.showsUserLocation = YES;//显示定位图
// 标准地图
self.mapView.mapType = BMKMapTypeStandard;
// 地图比例尺级别,在手机上当前可使用的级别为4-21级
self.mapView.zoomLevel = 16.0;
//设定地图View能否支持旋转 只有旋转地图才会出现指南针 不知道为什么
self.mapView.rotateEnabled = NO;
self.mapView.compassPosition = CGPointMake(20,20);
// self.mapView.mapPadding = UIEdgeInsetsMake(20, 20, 0, 0);
// 26.108768, 119.30714
// CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(26.108768, 119.30714);
// BMKCoordinateRegion region ;//表示范围的结构体
// region.center = coordinate;//中心点
// region.span.latitudeDelta = 0.038325;//经度范围(设置为0.1表示显示范围为0.2的纬度范围)
// region.span.longitudeDelta = 0.028045;//纬度范围
// 设置显示区域 中心点和范围
// [self.mapView setRegion:region animated:YES];
//这只是限制了地图大小
// [self.mapView setLimitMapRegion:region];
//自定义精度圈
BMKLocationViewDisplayParam *param = [[BMKLocationViewDisplayParam alloc] init];
// 精度圈 边框颜色
param.accuracyCircleStrokeColor = [UIColor colorWithRed:119/255.0 green:181/255.0 blue:254/255.0 alpha:0.6/1.0];
///精度圈 填充颜色
param.accuracyCircleFillColor = [UIColor colorWithRed:119/255.0 green:181/255. blue:254/255.0 alpha:0.2];
param.locationViewOffsetY = 0;//偏移量
param.locationViewOffsetX = 0;
param.locationViewImgName = @"icon_center_point";
[self.mapView updateLocationViewWithParam:param];
- 创建代理销毁
-(void)viewWillAppear:(BOOL)animated
{
[self.mapView viewWillAppear];
self.mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
self.locService.delegate = self;
}
-(void)viewWillDisappear:(BOOL)animated
{
[self.mapView viewWillDisappear];
self.mapView.delegate = nil; // 不用时,置nil
self.locService.delegate = nil;
[self.locService stopUserLocationService];//关闭定位服务
}
- 代理实现
#pragma mark BMKLocationServiceDelegate
/**
*在地图View将要启动定位时,会调用此函数
*@param mapView 地图View
*/
- (void)willStartLocatingUser
{
NSLog(@"start locate");
}
/**
*用户方向更新后,会调用此函数
*@param userLocation 新的用户位置
*/
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
// 动态更新我的位置数据
[self.mapView updateLocationData:userLocation];
NSLog(@"heading is %@",userLocation.heading);
}
/**
*用户位置更新后,会调用此函数 当前位置经纬度
*@param userLocation 新的用户位置
*/
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
[self.mapView updateLocationData:userLocation];
}
/**
*在地图View停止定位后,会调用此函数
*@param mapView 地图View
*/
- (void)didStopLocatingUser
{
NSLog(@"stop locate");
}
/**
*定位失败后,会调用此函数
*@param mapView 地图View
*@param error 错误号,参考CLError.h中定义的错误号
*/
- (void)didFailToLocateUserWithError:(NSError *)error
{
NSLog(@"location error");
}
- 自定义大头针
-(void)viewDidAppear:(BOOL)animated{
#pragma mark 创建大头针
//目的地
BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
annotation.coordinate = CLLocationCoordinate2DMake(26.108768, 119.30714);
annotation.title = @"这里是屏东城啊啊";
// 向地图窗口添加标注,需要实现BMKMapViewDelegate的-mapView:viewForAnnotation:函数来生成标注对应的View
[self.mapView addAnnotation:annotation];
self.pointAnnotation = annotation;
}
- 实现
#pragma mark BMKMapViewDelegate
/**
*根据anntation生成对应的View
*@param mapView 地图View
*@param annotation 指定的标注
*@return 生成的标注View
*/
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation{
if ([annotation isKindOfClass:[BMKPointAnnotation class]]){
//缓存机制
static NSString *reuseIndetifier = @"annotationReuseIndetifier";
BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
if (annotationView == nil){
annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:reuseIndetifier];
}
//自定义大头针图片
annotationView.image = [UIImage imageNamed:@"地图上的点"];
//选中该大头针 目的是一进来就默认选中 显示泡泡
[annotationView setSelected:YES animated:YES];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//取消指定的标注的选中状态,取消选中该annotation就会隐藏起泡泡
for (id <BMKAnnotation> annotation in self.mapView.annotations) {
if ([annotation isKindOfClass:[self.pointAnnotation class]]) {
[self.mapView deselectAnnotation:annotation animated:NO];
}
}
});
//自定义泡泡样式
// annotationView.paopaoView = [[BMKActionPaopaoView alloc] initWithCustomView:@"自定义泡泡样式类"];
// [self.mapView mapForceRefresh];
return annotationView;
}
return nil;
}
调起本机地图app
- 首先在 info.plist 里添加白名单, 否则无法正常跳转
- 跳转 URI 规则的说明地址
- 实现
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//检测手机是否安装这个地图应用
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
UIAlertAction *gaode = [UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// navi 服务类型 是 119.308456,26.108768
// sourceApplication 第三方调用应用名称。如applicationName 是
// poiname POI名称 否
// poiid 对应sourceApplication 的POI ID 否
// lat 纬度 是
// lon 经度 是
// dev 是否偏移(0:lat和lon是已经加密后的,不需要国测加密;1:需要国测加密) 是
// style 导航方式:(0:速度最快,1:费用最少,2:距离最短,3:不走高速,4:躲避拥堵,5:不走高速且避免收费,6:不走高速且躲避拥堵,7:躲避收费和拥堵,8:不走高速躲避收费和拥堵)
// 119.30714,26.098215
NSString *urlString = [NSString stringWithFormat:@"iosamap://path?sourceApplication=%@&sid=BGVIS1&slat=%f&slon=%f&sname=当前位置&did=BGVIS2&dlat=%f&dlon=%f&dname=&dev=%@0&t=0",@"高德地图",self.latitude,self.longitude,26.108768,119.308456,@"屏东城"];
//中文转码
NSString *encodedString = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)urlString, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
NULL, kCFStringEncodingUTF8));
//我用的是路线规划
NSURL *myLocationScheme = [NSURL URLWithString:encodedString];
if ([[UIDevice currentDevice].systemVersion integerValue] >= 10) { //iOS10以后,使用新API
[[UIApplication sharedApplication] openURL:myLocationScheme options:@{} completionHandler:^(BOOL success) {
NSLog(@"scheme调用结束"); }];
} else { //iOS10以前,使用旧API
[[UIApplication sharedApplication] openURL:myLocationScheme];
}
}];
[alert addAction:gaode];
}
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
UIAlertAction *baidu = [UIAlertAction actionWithTitle:@"百度地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
// baidumap://map/direction?origin=中关村&destination=五道口&mode=driving®ion=北京
// origin 起点
// destination zhong'dain
NSString *urlString = [NSString stringWithFormat:@"baidumap://map/direction?origin=name:%@|latlng:%f,%f&destination=name:%@|latlng:%f,%f&mode=driving&coord_type=gcj02&src=webapp.line.yourCompanyName.yourAppName",@"当前位置", self.latitude, self.longitude,@"屏东城", 26.108768, 119.30714];
NSString *encodedString = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)urlString, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
NULL, kCFStringEncodingUTF8));
NSURL *myLocationScheme = [NSURL URLWithString:encodedString];
if ([[UIDevice currentDevice].systemVersion integerValue] >= 10) { //iOS10以后,使用新API
[[UIApplication sharedApplication] openURL:myLocationScheme options:@{} completionHandler:^(BOOL success) {
NSLog(@"scheme调用结束"); }];
} else { //iOS10以前,使用旧API
[[UIApplication sharedApplication] openURL:myLocationScheme];
}
}];
[alert addAction:baidu];
}
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"qqmap://"]]) {
UIAlertAction *tencent = [UIAlertAction actionWithTitle:@"腾讯地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
NSString *urlString = [NSString stringWithFormat:@"qqmap://map/routeplan?from=当前位置&fromcoord=%f,%f&type=drive&tocoord=%f,%f&to=%@&coord_type=1&policy=0", self.latitude, self.longitude, 26.108768, 119.30714, @"屏东城"];
NSString *encodedString = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)urlString, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
NULL, kCFStringEncodingUTF8));
NSURL *myLocationScheme = [NSURL URLWithString:encodedString];
if ([[UIDevice currentDevice].systemVersion integerValue] >= 10) { //iOS10以后,使用新API
[[UIApplication sharedApplication] openURL:myLocationScheme options:@{} completionHandler:^(BOOL success) {
NSLog(@"scheme调用结束"); }];
} else { //iOS10以前,使用旧API
[[UIApplication sharedApplication] openURL:myLocationScheme];
}
}];
[alert addAction:tencent];
}
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"http://maps.apple.com/"]]) {
UIAlertAction *apple = [UIAlertAction actionWithTitle:@"iPhone自带地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//@26.108768,@119.308456
//起点119.30714,26.098215
MKMapItem *currentLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:CLLocationCoordinate2DMake((self.latitude),(self.longitude)) addressDictionary:nil]];
currentLocation.name =@"我的位置";
//目的地的位置
CLLocationCoordinate2D coords =CLLocationCoordinate2DMake((26.108768),(119.308456));
MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coords addressDictionary:nil]];
toLocation.name = @"屏东城";
NSArray *items = [NSArray arrayWithObjects:currentLocation, toLocation, nil];
NSDictionary *options = @{ MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsMapTypeKey: [NSNumber numberWithInteger:MKMapTypeStandard], MKLaunchOptionsShowsTrafficKey:@YES };
//打开苹果自身地图应用,并呈现特定的item
[MKMapItem openMapsWithItems:items launchOptions:options];
}];
[alert addAction:apple];
}
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
[alert addAction:cancel];
[self presentViewController:alert animated:YES completion:nil];