一翻伺、mapkit的基本使用
#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
/** */
@property (nonatomic, strong) CLLocationManager *lM;
@end
@implementation ViewController
- (CLLocationManager *)lM
{
if (!_lM) {
_lM = [[CLLocationManager alloc] init];
if ([_lM respondsToSelector:@selector(requestAlwaysAuthorization)])
{
[_lM requestAlwaysAuthorization];
}
}
return _lM;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
/**
MKMapTypeStandard = 0,
MKMapTypeSatellite,
MKMapTypeHybrid,
MKMapTypeSatelliteFlyover NS_ENUM_AVAILABLE(10_11, 9_0),
MKMapTypeHybridFlyover NS_ENUM_AVAILABLE(10_11, 9_0),
*/
// self.mapView.mapType = MKMapTypeSatelliteFlyover;
// self.mapView.zoomEnabled = NO;
//
//// self.mapView.showsCompass = NO;
// self.mapView.showsScale = YES;
[self lM];
// self.mapView.showsUserLocation = YES;
self.mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
}
@end
二、mapkit的中級(jí)使用
#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
/** */
@property (nonatomic, strong) CLLocationManager *lM;
@end
@implementation ViewController
- (CLLocationManager *)lM
{
if (!_lM) {
_lM = [[CLLocationManager alloc] init];
if ([_lM respondsToSelector:@selector(requestAlwaysAuthorization)])
{
[_lM requestAlwaysAuthorization];
}
}
return _lM;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
/**
MKMapTypeStandard = 0,
MKMapTypeSatellite,
MKMapTypeHybrid,
MKMapTypeSatelliteFlyover NS_ENUM_AVAILABLE(10_11, 9_0),
MKMapTypeHybridFlyover NS_ENUM_AVAILABLE(10_11, 9_0),
*/
// self.mapView.mapType = MKMapTypeSatelliteFlyover;
// self.mapView.zoomEnabled = NO;
//
//// self.mapView.showsCompass = NO;
// self.mapView.showsScale = YES;
[self lM];
self.mapView.delegate = self;
self.mapView.showsUserLocation = YES;
// self.mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
}
#pragma mark - MKMapViewDelegate
/**
* 更新到位置
*
* @param mapView 地圖
* @param userLocation 位置對(duì)象
*/
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
/**
* MKUserLocation (大頭針模型)
*
*
*/
userLocation.title = @"銀江軟件園";
userLocation.subtitle = @"城市寶";
// 設(shè)置地圖顯示中心
// [self.mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
// 設(shè)置地圖顯示區(qū)域
MKCoordinateSpan span = MKCoordinateSpanMake(0.051109, 0.034153);
MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate, span);
[self.mapView setRegion:region animated:YES];
}
三虹统、大頭針的添加
#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "XMGAnno.h"
@interface ViewController ()<MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
/** <#注釋#> */
@property (nonatomic, strong) CLGeocoder *geoC;
@end
@implementation ViewController
- (CLGeocoder *)geoC
{
if (!_geoC) {
_geoC = [[CLGeocoder alloc] init];
}
return _geoC;
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 1. 獲取當(dāng)前觸摸點(diǎn)
CGPoint point = [[touches anyObject] locationInView:self.mapView];
// 2. 轉(zhuǎn)換成經(jīng)緯度
CLLocationCoordinate2D pt = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
// 3. 添加大頭針
[self addAnnoWithPT:pt];
}
//-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
//{
// // 移除大頭針(模型)
// NSArray *annos = self.mapView.annotations;
// [self.mapView removeAnnotations:annos];
//}
- (void)addAnnoWithPT:(CLLocationCoordinate2D)pt
{
__block XMGAnno *anno = [[XMGAnno alloc] init];
anno.coordinate = pt;
anno.title = @"銀江軟件園";
anno.subtitle = @"城市寶";
anno.type = arc4random_uniform(5);
[self.mapView addAnnotation:anno];
CLLocation *loc = [[CLLocation alloc] initWithLatitude:anno.coordinate.latitude longitude:anno.coordinate.longitude];
[self.geoC reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
CLPlacemark *pl = [placemarks firstObject];
anno.title = pl.locality;
anno.subtitle = pl.thoroughfare;
}];
// 添加多個(gè)大頭針
// self.mapView addAnnotations:<#(nonnull NSArray<id<MKAnnotation>> *)#>
}
#pragma mark - MKMapViewDelegate
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
}
/**
* 當(dāng)我們添加大頭針模型時(shí),
*
* @param mapView 地圖
* @param annotation 大頭針
*
* @return 大頭針視圖
*/
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
// return nil;
static NSString *inden = @"datouzhen";
MKAnnotationView *pin = [mapView dequeueReusableAnnotationViewWithIdentifier:inden];
if (pin == nil) {
pin = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:inden];
}
pin.annotation = annotation;
// 設(shè)置是否彈出標(biāo)注
pin.canShowCallout = YES;
XMGAnno *anno = (XMGAnno *)annotation;
NSString *imageName = [NSString stringWithFormat:@"category_%zd", anno.type + 1];
pin.image = [UIImage imageNamed:imageName];
// 設(shè)置大頭針圖片(系統(tǒng)大頭針無效)
// pin.image = [UIImage imageNamed:@"category_5"];
pin.draggable = YES;
// pin.calloutOffset = CGPointMake(5, 8);
UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
iv.image = [UIImage imageNamed:@"htl"];
pin.leftCalloutAccessoryView = iv;
UIImageView *ivR = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
ivR.image = [UIImage imageNamed:@"eason"];
pin.rightCalloutAccessoryView = ivR;
pin.detailCalloutAccessoryView = [UISwitch new];
return pin;
}
- (MKPinAnnotationView *)systemAnnoWithMapView:(MKMapView *)mapView andAnno:(id<MKAnnotation>)annotation
{
static NSString *inden = @"datouzhen";
MKPinAnnotationView *pin = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:inden];
if (pin == nil) {
pin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:inden];
}
pin.annotation = annotation;
// 設(shè)置是否彈出標(biāo)注
pin.canShowCallout = YES;
// 設(shè)置大頭針顏色
pin.pinTintColor = [UIColor blackColor];
// 從天而降
pin.animatesDrop = YES;
// 設(shè)置大頭針圖片(系統(tǒng)大頭針無效)
// pin.image = [UIImage imageNamed:@"category_5"];
pin.draggable = YES;
return pin;
}
// 不選中
-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
NSLog(@"不選中");
NSLog(@"%@", view.annotation);
}
// 選中
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
NSLog(@"選中");
}
@end
四弓坞、利用系統(tǒng)App導(dǎo)航|3D視角|地圖快照截圖
#import "ViewController.h"
#import <MapKit/MapKit.h>
@interface ViewController ()
/** */
@property (nonatomic, strong) CLGeocoder *geoC;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@end
@implementation ViewController
- (CLGeocoder *)geoC
{
if (!_geoC) {
_geoC = [[CLGeocoder alloc] init];
}
return _geoC;
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 3D視角
// MKMapCamera *camer = [MKMapCamera cameraLookingAtCenterCoordinate:CLLocationCoordinate2DMake(23.132931, 113.375924) fromEyeCoordinate:CLLocationCoordinate2DMake(23.135931, 113.375924) eyeAltitude:10];
// self.mapView.camera = camer;
//地圖快照截圖
MKMapSnapshotOptions *option = [[MKMapSnapshotOptions alloc] init];
// 針對(duì)地圖
option.region = self.mapView.region;
option.showsBuildings = YES;
// 輸出圖片
option.size = CGSizeMake(1000, 2000);
option.scale = [UIScreen mainScreen].scale;
MKMapSnapshotter *snap = [[MKMapSnapshotter alloc] initWithOptions:option];
[snap startWithCompletionHandler:^(MKMapSnapshot * _Nullable snapshot, NSError * _Nullable error) {
if (error == nil) {
UIImage *image = snapshot.image;
NSData *data = UIImagePNGRepresentation(image);
[data writeToFile:@"/Users/xiaomage/Desktop/map.png" atomically:YES];
}else
{
NSLog(@"--%@", error.localizedDescription);
}
}];
}
- (void)begNav
{
[self.geoC geocodeAddressString:@"廣州" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
// 廣州地標(biāo)
CLPlacemark *gzP = [placemarks firstObject];
[self.geoC geocodeAddressString:@"上海" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
// 上海地標(biāo)
CLPlacemark *shP = [placemarks firstObject];
[self beginNavWithBpl:gzP andEndP:shP];
}];
}];
}
- (void)beginNavWithBpl:(CLPlacemark *)beginP andEndP:(CLPlacemark *)endP
{
// 創(chuàng)建開始的地圖項(xiàng)
CLPlacemark *clPB = beginP;
MKPlacemark *mkPB = [[MKPlacemark alloc] initWithPlacemark:clPB];
MKMapItem *beginI = [[MKMapItem alloc] initWithPlacemark:mkPB];
// 創(chuàng)建結(jié)束的地圖項(xiàng)
CLPlacemark *clP = endP;
MKPlacemark *mkP = [[MKPlacemark alloc] initWithPlacemark:clP];
MKMapItem *endI = [[MKMapItem alloc] initWithPlacemark:mkP];
// 地圖項(xiàng)數(shù)組
NSArray *items = @[beginI, endI];
// 啟動(dòng)字典
NSDictionary *dic = @{
// 導(dǎo)航方式
MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving,
// 地圖類型
MKLaunchOptionsMapTypeKey : @(MKMapTypeHybrid),
// 是否顯示交通
MKLaunchOptionsShowsTrafficKey : @(YES)
};
[MKMapItem openMapsWithItems:items launchOptions:dic];
}
@end
五、獲取導(dǎo)航路線信息
#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()
/** */
@property (nonatomic, strong) CLGeocoder *geoC;
@end
@implementation ViewController
- (CLGeocoder *)geoC
{
if (!_geoC) {
_geoC = [[CLGeocoder alloc] init];
}
return _geoC;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.geoC geocodeAddressString:@"廣州" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
CLPlacemark *gzP = [placemarks firstObject];
[self.geoC geocodeAddressString:@"shanghai" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
CLPlacemark *shP = [placemarks firstObject];
[self getRouteWithBeginPL:gzP andEndPL:shP];
}];
}];
}
- (void)getRouteWithBeginPL:(CLPlacemark *)beginP andEndPL:(CLPlacemark *)endPL
{
MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
// 起點(diǎn)
CLPlacemark *clP = beginP;
MKPlacemark *mkP = [[MKPlacemark alloc] initWithPlacemark:clP];
MKMapItem *sourceItem = [[MKMapItem alloc] initWithPlacemark:mkP];
request.source = sourceItem;
// 終點(diǎn)
CLPlacemark *clP2 = endPL;
MKPlacemark *mkP2 = [[MKPlacemark alloc] initWithPlacemark:clP2];
MKMapItem *endItem = [[MKMapItem alloc] initWithPlacemark:mkP2];
request.destination = endItem;
MKDirections *direction = [[MKDirections alloc] initWithRequest:request];
[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * _Nullable response, NSError * _Nullable error) {
/**
* MKDirectionsResponse
routes : 路線數(shù)組MKRoute
*/
/**
* MKRoute
name : 路線名稱
distance : 距離
expectedTravelTime : 預(yù)期時(shí)間
polyline : 折線(數(shù)據(jù)模型)
steps
*/
/**
* steps <MKRouteStep *>
instructions : 行走提示
*/
// NSLog(@"%@", response);
[response.routes enumerateObjectsUsingBlock:^(MKRoute * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@---%zd---%f", obj.name, obj.expectedTravelTime, obj.distance);
[obj.steps enumerateObjectsUsingBlock:^(MKRouteStep * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@", obj.instructions);
}];
}];
}];
}
@end
六车荔、繪制路線信息
#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<MKMapViewDelegate>
/** */
@property (nonatomic, strong) CLGeocoder *geoC;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@end
@implementation ViewController
- (CLGeocoder *)geoC
{
if (!_geoC) {
_geoC = [[CLGeocoder alloc] init];
}
return _geoC;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.geoC geocodeAddressString:@"廣州" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
CLPlacemark *gzP = [placemarks firstObject];
[self.geoC geocodeAddressString:@"shanghai" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
CLPlacemark *shP = [placemarks firstObject];
[self getRouteWithBeginPL:gzP andEndPL:shP];
}];
}];
}
- (void)getRouteWithBeginPL:(CLPlacemark *)beginP andEndPL:(CLPlacemark *)endPL
{
MKCircle *circle = [MKCircle circleWithCenterCoordinate:beginP.location.coordinate radius:100000];
[self.mapView addOverlay:circle];
MKCircle *circle2 = [MKCircle circleWithCenterCoordinate:endPL.location.coordinate radius:100000];
[self.mapView addOverlay:circle2];
MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
// 起點(diǎn)
CLPlacemark *clP = beginP;
MKPlacemark *mkP = [[MKPlacemark alloc] initWithPlacemark:clP];
MKMapItem *sourceItem = [[MKMapItem alloc] initWithPlacemark:mkP];
request.source = sourceItem;
// 終點(diǎn)
CLPlacemark *clP2 = endPL;
MKPlacemark *mkP2 = [[MKPlacemark alloc] initWithPlacemark:clP2];
MKMapItem *endItem = [[MKMapItem alloc] initWithPlacemark:mkP2];
request.destination = endItem;
MKDirections *direction = [[MKDirections alloc] initWithRequest:request];
[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * _Nullable response, NSError * _Nullable error) {
/**
* MKDirectionsResponse
routes : 路線數(shù)組MKRoute
*/
/**
* MKRoute
name : 路線名稱
distance : 距離
expectedTravelTime : 預(yù)期時(shí)間
polyline : 折線(數(shù)據(jù)模型)
steps
*/
/**
* steps <MKRouteStep *>
instructions : 行走提示
*/
// NSLog(@"%@", response);
[response.routes enumerateObjectsUsingBlock:^(MKRoute * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@---%zd---%f", obj.name, obj.expectedTravelTime, obj.distance);
MKPolyline *polyline = obj.polyline;
// 添加一個(gè)覆蓋層數(shù)據(jù)模型
[self.mapView addOverlay:polyline];
}];
}];
}
#pragma mark - MKMapViewDelegate
/**
* 獲取對(duì)應(yīng)的圖層渲染
*
* @param mapView 地圖
* @param overlay 覆蓋層數(shù)據(jù)模型
*
* @return 圖層渲染
*/
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
if ([overlay isKindOfClass:[MKCircle class]]) {
MKCircleRenderer *circleR = [[MKCircleRenderer alloc] initWithOverlay:overlay];
circleR.fillColor = [UIColor cyanColor];
circleR.alpha = 0.5;
return circleR;
}
if ([overlay isKindOfClass:[MKPolyline class]])
{
MKPolylineRenderer *render = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
// 設(shè)置線寬
render.lineWidth = 10;
// 設(shè)置顏色
render.strokeColor = [UIColor redColor];
return render;
}
return nil;
}