MapKit基本应用
//创建地图
_mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:_mapView];
//设置地图类型
//Standard 标准地图
//Satellite 卫星地图
//Hybrid 混合模式
_mapView.mapType = MKMapTypeStandard;
//将地图定位到指定的位置
//参数1:MKCoordinateRegion想要锁定的位置信息(CLLocationCoordinate2D经纬度,MKCoordinateSpan放大系数)
[_mapView setRegion:MKCoordinateRegionMake(CLLocationCoordinate2DMake(30.67, 104.06), MKCoordinateSpanMake(0.01, 0.01)) animated:YES];
//是否可以缩放
_mapView.zoomEnabled = true;
//是否可以滚动
_mapView.scrollEnabled = true;
//是否可以旋转
_mapView.rotateEnabled = true;
//是否显示指南针
_mapView.showsCompass = true;
//是否显示建筑
_mapView.showsBuildings = true;
//是否显示交通
_mapView.showsTraffic = true;
//是否显示比例尺
_mapView.showsScale = true;
//不跟踪用户的位置
_mapView.userTrackingMode = MKUserTrackingModeNone;
//跟踪用户位置并在地图上显示
_mapView.userTrackingMode = MKUserTrackingModeFollow;
//跟踪用户的位置并根据用户前进的方向进行旋转
_mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
//设置代理
_mapView.delegate = self;
//创建大头针大头针
MKPointAnnotation * annotation = [[MKPointAnnotation alloc] init];
//设置大头针位置
annotation.coordinate = CLLocationCoordinate2DMake(30.67, 104.06);
//设置大头针的标题
annotation.title = @"成都";
annotation.subtitle = @"双流";
[_mapView addAnnotation:annotation];
//创建CLGeocoder地理编码对象
CLGeocoder * geocoder = [[CLGeocoder alloc] init];
//根据输入地址进行反编码
[geocoder geocodeAddressString:@"四川成都青羊区" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//拿到编码的地址
_mark1 = [placemarks firstObject];
_label.text = [NSString stringWithFormat:@"%f", _mark1.location.coordinate.latitude];
}];
[geocoder geocodeAddressString:@"四川成都双流县" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
_mark2 = [placemarks firstObject];
}];
//调用系统的导航
[self beginNavWithBeginPlacemark:_mark1 andEndPlacemark:_mark2];
- (void)beginNavWithBeginPlacemark:(CLPlacemark *)beginPlacemark andEndPlacemark:(CLPlacemark *)endPlacemark{
// 创建起点:根据 CLPlacemark 地标对象创建 MKPlacemark 地标对象
MKPlacemark *itemP1 = [[MKPlacemark alloc] initWithPlacemark:beginPlacemark];
MKMapItem *item1 = [[MKMapItem alloc] initWithPlacemark:itemP1];
// 创建终点:根据 CLPlacemark 地标对象创建 MKPlacemark 地标对象
MKPlacemark *itemP2 = [[MKPlacemark alloc] initWithPlacemark:endPlacemark];
MKMapItem *item2 = [[MKMapItem alloc] initWithPlacemark:itemP2];
NSDictionary *launchDic = @{
// 设置导航模式参数
MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving,
// 设置地图类型
MKLaunchOptionsMapTypeKey : @(MKMapTypeHybrid),
// 设置是否显示交通
MKLaunchOptionsShowsTrafficKey : @(YES),
};
// 根据 MKMapItem 数组 和 启动参数字典 来调用系统地图进行导航
[MKMapItem openMapsWithItems:@[item1, item2] launchOptions:launchDic];
}
网友评论