iOS MKMapView显示地址及路线

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/JennyHermes/article/details/77677807

导读:本篇博文实现两点:
(1)根据地名在地图上显示位置
(2)打开系统地图查看周边及路线图

注意:要在info.plist里面添加 NSLocationWhenInUseDescription 和 Privacy - Location Always Usage Description,两个参数值都是YES

#import "THMapViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
//这个是用于显示大头针效果
#import "THMapLocation.h"


@interface THMapViewController()<CLLocationManagerDelegate,MKMapViewDelegate>
/**
 *  地图
 */
@property(strong, nonatomic) MKMapView *mapview;

@property (nonatomic, strong) CLLocationManager *locationManager;

/**
 创建一个地理编码器,来实现编码和反编码
 */
@property (nonatomic, strong) CLGeocoder *geocoder;
@end

@implementation THMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"活动地图";

    [self setMapView];

    _geocoder=[[CLGeocoder alloc]init];

    [self getLocation];

}
/**
 创建ui
 */
- (void)setMapView{

    //地图
    MKMapView *mapview =[[MKMapView alloc]init];
    mapview.size = CGSizeMake(THScreenW, THfloat(475));
    mapview.x = 0;
    mapview.y = 0;
    mapview.mapType = MKMapTypeStandard ;
    mapview.scrollEnabled = YES;
    mapview.delegate = self;
    self.mapview = mapview;
    [self.scrollView addSubview:mapview];

    //查看路线
    UIButton *btnFind = [[UIButton alloc]initWithFrame:CGRectMake(THScreenW/2-THfloat(100), CGRectGetMaxY(mapview.frame)+THfloat(7), THfloat(200), THfloat(18))];
    [btnFind setImage:[UIImage imageNamed:@"activity_area"] forState:UIControlStateNormal];
    [btnFind setTitle:@"查看路线及周边" forState:UIControlStateNormal];
    [btnFind setTitleColor:[UIColor hexChangeFloat:@"333333"] forState:UIControlStateNormal];
    btnFind.titleLabel.font = [UIFont systemFontOfSize:THfloat(14)];
    [btnFind addTarget:self action:@selector(turnByTurn) forControlEvents:UIControlEventTouchUpInside];
    [btnFind setTitleEdgeInsets:UIEdgeInsetsMake(0,btnFind.imageView.frame.size.height+THfloat(14), 0.0,0.0)];
    [btnFind setImageEdgeInsets:UIEdgeInsetsMake(0,0,0.0,btnFind.titleLabel.frame.size.height)];
    btnFind.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [scrollView addSubview:btnFind];

}


/**
 在地图上定位活动地址
 */
- (void)getLocation{
    [_geocoder geocodeAddressString:@"北京市" completionHandler:^(NSArray *placemarks, NSError *error) {
        NSLog(@"查询记录数: %lu",(unsigned long)[placemarks count]);

        if ([placemarks count ] > 0) {
            //移除目前地图上得所有标注点
            [self.mapview removeAnnotations:self.mapview.annotations];

        }
        for (int i = 0; i< [placemarks count]; i++) {
            CLPlacemark * placemark = placemarks[i];

            //调整地图位置和缩放比例,第一个参数是目标区域的中心点,第二个参数:目标区域南北的跨度,第三个参数:目标区域的东西跨度,单位都是米
            MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(placemark.location.coordinate, 10000, 10000);

            //重新设置地图视图的显示区域
            [self.mapview setRegion:viewRegion animated:YES];

            // 实例化 MapLocation 对象
            THMapLocation * annotation = [[THMapLocation alloc] init];
            annotation.streetAddress = placemark.thoroughfare ;
            annotation.city = placemark.locality;
            annotation.state = placemark.administrativeArea ;
            annotation.zip = placemark.postalCode;
            annotation.coordinate = placemark.location.coordinate;

            //把标注点MapLocation 对象添加到地图视图上,一旦该方法被调用,地图视图委托方法mapView:ViewForAnnotation:就会被回调
            [self.mapview addAnnotation:annotation];
        }


    }];
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    self.mapview.centerCoordinate = userLocation.location.coordinate;
}

- (void)mapViewDidFailLoadingMap:(MKMapView *)theMapView withError:(NSError *)error {
    NSLog(@"error : %@",[error description]);
}

/**
 打开系统地图查看路线
 */
- (void)turnByTurn{

        //地理编码
        [_geocoder geocodeAddressString:@"北京市" completionHandler:^(NSArray *placemarks, NSError *error) {
            CLPlacemark *clPlacemark2=[placemarks firstObject];//获取第一个地标
            MKPlacemark *mkPlacemark2=[[MKPlacemark alloc]initWithPlacemark:clPlacemark2];
            NSDictionary *options=@{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard),MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving};
            MKMapItem *mapItem1=[MKMapItem mapItemForCurrentLocation];//当前位置
            MKMapItem *mapItem2=[[MKMapItem alloc]initWithPlacemark:mkPlacemark2];
            [MKMapItem openMapsWithItems:@[mapItem1,mapItem2] launchOptions:options];
    }];
}

-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    [self.mapview removeFromSuperview];
    [self.view addSubview:mapView];
    [self applyMapViewMemoryHotFix];
}

- (void)dealloc {
    self.mapview.showsUserLocation = NO;
    self.mapview.userTrackingMode = MKUserTrackingModeNone;
    [self.mapview.layer removeAllAnimations];
    [self.mapview removeAnnotations:self.mapview.annotations];
    [self.mapview removeOverlays:self.mapview.overlays];
    [self.mapview removeFromSuperview];
    self.mapview.delegate = nil;
    self.mapview = nil;
}

- (void)applyMapViewMemoryHotFix{
    switch (self.mapview.mapType){
        case MKMapTypeHybrid:
        {
            self.mapview.mapType = MKMapTypeStandard;
        }
        break;
        case MKMapTypeStandard:
        {
            self.mapview.mapType = MKMapTypeHybrid;
        } break;
        default:
        break;
    }
    self.mapview.mapType = MKMapTypeStandard;
}


/*
 **
 * @file: THMapLocation
 * @brief:地图
 * Copyright: Copyright (c) 2017
 *
 * @date: 2017-08-29
 **/

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>  

@interface THMapLocation : NSObject<MKAnnotation>

// 地图标点类必须实现 MKAnnotation 协议
// 地理坐标
@property (nonatomic ,readwrite) CLLocationCoordinate2D coordinate ;

//街道属性信息
@property (nonatomic , copy) NSString * streetAddress ;

// 城市信息属性
@property (nonatomic ,copy) NSString * city ;

// 州,省 市 信息

@property(nonatomic ,copy ) NSString * state ;
//邮编
@property (nonatomic ,copy) NSString * zip  ;
@end


*.m文件*
#import "THMapLocation.h"

@implementation THMapLocation
#pragma mark 标点上的主标题
- (NSString *)title{
    return @"活动位置!";
}

#pragma  mark 标点上的副标题
- (NSString *)subtitle{
    NSMutableString *ret = [NSMutableString new];
    if (_state) {
        [ret appendString:_state];
    }
    if (_city) {
        [ret appendString:_city];
    }
    if (_city && _state) {
        [ret appendString:@", "];
    }
    if (_streetAddress && (_city || _state || _zip)) {
        [ret appendString:@" · "];
    }
    if (_streetAddress) {
        [ret appendString:_streetAddress];
    }
    if (_zip) {
        [ret appendFormat:@",  %@",_zip];
    }
    return ret;
}

demo下载地址:http://code.cocoachina.com/view/135984

猜你喜欢

转载自blog.csdn.net/JennyHermes/article/details/77677807