Mapkit

Posted 谢小锋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mapkit相关的知识,希望对你有一定的参考价值。

//
//  ViewController.m
//  MapKit
//
//  Created by 谢泽锋 on 2016/10/27.
//  Copyright ? 2016年 xiezefeng. All rights reserved.
//


#import "XZFAnno.h"
#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<MKMapViewDelegate>
@property(nonatomic,strong)MKMapView * myMapView;
@property(nonatomic,strong)CLLocationManager * lm;
@property(nonatomic,strong)CLGeocoder * geoc;
@property(nonatomic,strong)MKDirections * direction;
@end

@implementation ViewController
-(MKDirections *)direction
{
    if (!_direction) {
        _direction=[[MKDirections alloc]init];
    }
    return _direction;
}
-(CLGeocoder *)geoc
{
    if (!_geoc) {
        _geoc=[[CLGeocoder alloc]init];
    }
    return _geoc;
}
-(CLLocationManager *)lm
{
    if (!_lm) {
        _lm=[[CLLocationManager alloc]init];
    }
    return _lm;
}
-(MKDirectionsRequest * )start:(CLPlacemark*)start end:(CLPlacemark*)end
{
    
    MKCircle * circle = [MKCircle circleWithCenterCoordinate:start.location.coordinate radius:1000];
    [self.myMapView addOverlay:circle];
    
    MKDirectionsRequest * request =[[MKDirectionsRequest alloc]init];
    CLPlacemark * clp =start;
    MKPlacemark * mkp = [[MKPlacemark alloc]initWithPlacemark:clp];
    MKMapItem * source = [[MKMapItem alloc]initWithPlacemark:mkp];
    request.source = source;
//
    
    CLPlacemark * clp1 =end;
    MKPlacemark * mkp1 = [[MKPlacemark alloc]initWithPlacemark:clp1];
    MKMapItem * source1 = [[MKMapItem alloc]initWithPlacemark:mkp1];
    request.destination = source1;
    return request;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
 
   
  
    
    
    
    
    
    _myMapView = [[MKMapView alloc]initWithFrame:self.view.frame];
    [self.view addSubview:_myMapView];
//        [_lm requestAlwaysAuthorization];
//        [_lm startUpdatingLocation];

    [self.lm requestAlwaysAuthorization];
 
    
//        [self.lm requestWhenInUseAuthorization];
    
    //    _myMapView.mapType = MKMapTypeHybridFlyover;//地图类型
    //    self.myMapView.zoomEnabled = NO;//缩放
    //    self.myMapView.scrollEnabled = NO;
    //    self.myMapView.showsScale = YES;//比例尺
    self.myMapView.showsUserLocation = YES;
    self.myMapView.userTrackingMode = MKUserTrackingModeFollow;//追踪
    self.myMapView.userLocation.title = @"";
    self.myMapView.delegate = self;

}
//-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    NSArray * annos = self.myMapView.annotations;
//    //移除大头针
//    [self.myMapView removeAnnotations:annos];
//}

-(void)beginNavWithBpl:(CLPlacemark*)beginP andEndOption:(CLPlacemark*)endp{
//    CLPlacemark * clp =[[CLPlacemark alloc]init];
    
    MKPlacemark * mkp = [[MKPlacemark alloc]initWithPlacemark:beginP];
    MKMapItem * begin= [[MKMapItem alloc]initWithPlacemark:mkp];
    
    
    
    
    MKPlacemark * mkpe = [[MKPlacemark alloc]initWithPlacemark:endp];
    MKMapItem * end= [[MKMapItem alloc]initWithPlacemark:mkpe];
    

        //导航方式
        NSDictionary * dic = @{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeWalking,
                               MKLaunchOptionsMapTypeKey:@(MKMapTypeHybrid),
                               //是否显示交通
                               MKLaunchOptionsShowsTrafficKey:@(YES)
                               };
        [MKMapItem openMapsWithItems:@[begin,end] launchOptions:dic];
        

}
//当我添加一个覆盖层图层渲染
//渲染图层overlay
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
   
    if ([overlay isKindOfClass:[MKCircle class]]) {
        MKCircleRenderer * circler = [[MKCircleRenderer alloc]initWithOverlay:overlay];
        circler.fillColor =[UIColor orangeColor];
        circler.lineWidth = 1;
        return circler;
    }
   
    
    
    MKPolylineRenderer * OverlayRenderer = [[MKPolylineRenderer alloc]initWithOverlay:overlay];
    
    OverlayRenderer.lineWidth=3;
    OverlayRenderer.strokeColor = [UIColor redColor];
    return OverlayRenderer;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    
    [self.geoc geocodeAddressString:@"广州" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark * gzp1 = [placemarks firstObject];
        [self.geoc geocodeAddressString:@"上海" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            CLPlacemark * gzp2 = [placemarks firstObject];
            
            _direction = [[MKDirections alloc]initWithRequest:[self start:gzp1 end:gzp2]];
            
            [_direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * _Nullable response, NSError * _Nullable error) {
               //response rule 路线数组
                //MKRoute polyline 折线(数据模型)
               [response.routes enumerateObjectsUsingBlock:^(MKRoute * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                   NSLog(@"%f",obj.distance);
                   [obj.steps enumerateObjectsUsingBlock:^(MKRouteStep * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                       NSLog(@"%@",obj.instructions);
                       MKPolyline * poly = obj.polyline;
                       [self.myMapView addOverlay:poly];

                   }];
               }];
                NSLog(@"response%@",response);
                
            }];
            
        }];
    }];
    
    
    
//    MKMapCamera * camer = [MKMapCamera cameraLookingAtCenterCoordinate:CLLocationCoordinate2DMake(23, 113) fromEyeCoordinate:CLLocationCoordinate2DMake(23.1, 113) eyeAltitude:10];
//    self.myMapView.camera = camer;
//    
    #pragma mark 跳转至原生定位
//    [self.geoc geocodeAddressString:@"广州" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//        CLPlacemark * gzp1 = [placemarks firstObject];
//        [self.geoc geocodeAddressString:@"上海" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//            CLPlacemark * gzp2 = [placemarks firstObject];
//            [self beginNavWithBpl:gzp1 andEndOption:gzp2];
//            
//        }];
//    }];
//    
  
    
    

    CGPoint point = [[touches anyObject]locationInView:_myMapView];
    CLLocationCoordinate2D  pt = [self.myMapView convertPoint:point toCoordinateFromView:_myMapView];
    [self addAnnooWithPT:pt];
    //    [self.myMapView addAnnotation:<#(nonnull id<MKAnnotation>)#>
}
-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
        NSArray * annos = self.myMapView.annotations;
    //    //移除大头针
        [self.myMapView removeAnnotation:annos.lastObject];
}
//-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
//    return nil;
//}
#pragma mark 添加大头针
-(void)addAnnooWithPT:(CLLocationCoordinate2D)dd {
    
    
    XZFAnno * anno = [XZFAnno new];
    XZFAnno * me = self.myMapView.annotations.firstObject;
    me.title = @"";
    
//    anno.coordinate = self.myMapView.centerCoordinate;
    anno.coordinate = dd;
    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.thoroughfare;
        anno.subtitle = pl.locality;
        [self.myMapView addAnnotation:anno];
        
    
    }];
  
}
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{

    
    
//  XZFAnno*annotat = (XZFAnno*)annotation;
//   [email protected]"";
    static NSString * inden = @"datouzhen";
    MKAnnotationView * pin = (MKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:inden];
    
    if (!pin) {
        pin=  [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:inden];
    };
    pin.draggable=YES;
    //是否显示标注
    pin.canShowCallout = YES;
    //系统大头针失效
    pin.image = [UIImage imageNamed:@"location"];
  
    pin.annotation = annotation;
    NSLog(@"%@",annotation.title);
    if ([annotation.title isEqualToString:@""]) {
        pin.image = [UIImage imageNamed:@""];

    }
//    pin.calloutOffset = CGPointMake(20, 0);
    UIImageView * leftImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    leftImage.image = [UIImage imageNamed:@"1.jpg"];
    UIImageView * rightImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    rightImage.image = [UIImage imageNamed:@"1.jpg"];
    pin.leftCalloutAccessoryView = leftImage;
    pin.rightCalloutAccessoryView = rightImage;
    UIView* center = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    center.backgroundColor = [UIColor orangeColor];
//    pin.detailCalloutAccessoryView = center;
    
    return pin;
}
#pragma mark 选中大头针
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
}
 #pragma mark  系统大头针
-(MKAnnotationView *)systemMapview:(MKMapView*)mapView andAnnotation:(id<MKAnnotation>)annotation
{
    
    static NSString * inden = @"datouzhen";
    MKPinAnnotationView * pin = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:inden];
    if (!pin) {
        pin=  [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:inden];
    };
    pin.animatesDrop = YES;
    pin.draggable=YES;
    //是否显示标注
    pin.canShowCallout = YES;
    //系统大头针失效
    //    pin.image = [UIImage imageNamed:@"QQ"];
    pin.pinColor = MKPinAnnotationColorGreen;
    if ([pin respondsToSelector:@selector(pinTintColor)]) {
        pin.pinTintColor = [UIColor orangeColor];//ios9
        
    }
    pin.annotation = annotation;
    
    return pin;
}


#pragma mark 更新到位置

//-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
//
//    //设置地图显示中心
//     [self.myMapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
////设置显示
//    MKCoordinateSpan span = MKCoordinateSpanMake(0.0001, 0.001);
//    MKCoordinateRegion  region = MKCoordinateRegionMake(userLocation.location.coordinate, span);
//    [self.myMapView setRegion:region];
//
//}
//-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
//    
//    NSLog(@"%f------%f",mapView.region.span.longitudeDelta,mapView.region.span.latitudeDelta);
//    
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

 

以上是关于Mapkit的主要内容,如果未能解决你的问题,请参考以下文章

TableCell 转为 mapkit

Swift 中的 MapKit

自定义注释苹果mapkit

在 mapkit 中显示自定义注释

MapKit 中的无效区域错误

MapKit 的注释问题