iOS开发MapKit地图两点之间的距离及线路的绘制

//建一个model类
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface MyAnnotation : NSObject<MKAnnotation>
@property (nonatomic ,assign) CLLocationCoordinate2D coordinate;
@property (nonatomic,copy)NSString *myTitle;
@property (nonatomic,copy)NSString *mySubtitle;

- (id)initWithCoordinate2D:(CLLocationCoordinate2D)coordinate;
@end


#import "MyAnnotation.h"
@implementation MyAnnotation
- (id)initWithCoordinate2D:(CLLocationCoordinate2D)coordinate
{
    if (self = [super init]) {
        _coordinate = coordinate;
    }
    return self;
}
- (NSString *)title
{
    return _myTitle;
}
- (NSString *)subtitle
{
    return _mySubtitle;
}
@end

#import "KYViewController.h"
#import <MapKit/MapKit.h>
#import "MyAnnotation.h"

@interface KYViewController ()<MKMapViewDelegate, CLLocationManagerDelegate, UITextFieldDelegate>
{
    CLLocationManager *locationManager;
    //2点之间的线路
    CLLocationCoordinate2D fromCoordinate;
    CLLocationCoordinate2D toCoordinate;
    //计算2点之间的距离
    CLLocation *newLocation;
    CLLocation *oldLocation;
    IBOutlet UILabel *titlelabel;
}
@property (weak, nonatomic) IBOutlet UITextField *txtQueryKey;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;

@end

@implementation KYViewController

- (void)viewWillAppear:(BOOL)animated
{
    //开始定位
    [locationManager startUpdatingLocation];
    _txtQueryKey.delegate = self;

}

- (void)viewWillDisappear:(BOOL)animated
{
    _mapView.delegate = nil;
    locationManager.delegate = nil;
    _txtQueryKey.delegate = nil;
    //停止定位
    [locationManager stopUpdatingLocation];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    //初始化地图
    [self initWithMapView];
    //初始化定位服务管理对象
    [self initWithLocationManager];

}

- (void)initWithMapView
{
    //设置地图类型
    _mapView.mapType = MKMapTypeStandard;
    //设置代理
    _mapView.delegate = self;
    //开启自动定位
    _mapView.showsUserLocation = YES;
    [_mapView setUserTrackingMode:(MKUserTrackingModeFollow) animated:YES];
}
- (void)initWithLocationManager
{
    //初始化定位服务管理对象
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    [locationManager requestAlwaysAuthorization];
    //设置精确度
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置设备移动后获取位置信息的最小距离。单位为米
    locationManager.distanceFilter = 10.0f;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_txtQueryKey resignFirstResponder];
    return YES;
}

//位置的实时更新
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{

    fromCoordinate = CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    _mapView.centerCoordinate = userLocation.location.coordinate;
//    CLLocationCoordinate2D center = userLocation.location.coordinate;
//    MKCoordinateSpan span = MKCoordinateSpanMake(0.021321, 0.019366);//这个显示大小精度自己调整
//    MKCoordinateRegion region = MKCoordinateRegionMake(center, span);
//    [mapView setRegion:region animated:YES];

    CLLocation *locNow = [[CLLocation alloc]initWithLatitude:userLocation.location.coordinate.latitude longitude:userLocation.location.coordinate.longitude];
    CLGeocoder *geocoder=[[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:locNow completionHandler:^(NSArray *placemarks,NSError *error)
     {
         CLPlacemark *placemark=[placemarks objectAtIndex:0];
         oldLocation = placemark.location;
         CLLocationCoordinate2D coordinate;
         coordinate.latitude = userLocation.location.coordinate.latitude;
         coordinate.longitude = userLocation.location.coordinate.longitude;
         MyAnnotation *annotation = [[MyAnnotation alloc] init];
         //设置中心
         annotation.coordinate = coordinate;
         //触发viewForAnnotation

         //设置显示范围
         MKCoordinateRegion region;
         region.span.latitudeDelta = 0.011111;
         region.span.longitudeDelta = 0.011111;
         region.center = coordinate;
         // 设置显示位置(动画)
         [_mapView setRegion:region animated:YES];
         // 设置地图显示的类型及根据范围进行显示
         [_mapView regionThatFits:region];
         _mapView.showsUserLocation = NO;
         annotation.myTitle = @"我的位置";
         annotation.mySubtitle = [NSString stringWithFormat:@"%@, %@, %@",placemark.locality,placemark.administrativeArea,placemark.thoroughfare];
         annotation.coordinate = placemark.location.coordinate;
         [_mapView addAnnotation:annotation];
     }];


}

//计算2点之间的距离
- (IBAction)calculationDistance:(id)sender {

    CGFloat distance = [newLocation distanceFromLocation:oldLocation];
    NSLog(@"distance = %f", distance);
    titlelabel.text = [NSString stringWithFormat:@"%f米", distance];
}

//线路的绘制
- (IBAction)lineDrawing:(id)sender {

    MKPlacemark *fromPlacemark = [[MKPlacemark alloc] initWithCoordinate:fromCoordinate addressDictionary:nil];
    MKPlacemark *toPlacemark = [[MKPlacemark alloc] initWithCoordinate:toCoordinate addressDictionary:nil];
    MKMapItem *fromItem = [[MKMapItem alloc] initWithPlacemark:fromPlacemark];
    MKMapItem *toItem = [[MKMapItem alloc] initWithPlacemark:toPlacemark];
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
    request.source = fromItem;
    request.destination = toItem;
    request.requestsAlternateRoutes = YES;
    MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
    [directions calculateDirectionsWithCompletionHandler:
     ^(MKDirectionsResponse *response, NSError *error) {
         if (error) {
             NSLog(@"error:%@", error);
         }
         else {
             MKRoute *route = response.routes[0];
             [self.mapView addOverlay:route.polyline];
         }
     }];

}
//线路的绘制
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView
            rendererForOverlay:(id<MKOverlay>)overlay
{
    MKPolylineRenderer *renderer;
    renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
    renderer.lineWidth = 5.0;
    renderer.strokeColor = [UIColor purpleColor];

    return renderer;
}

//地理信息编码查询
- (IBAction)handleButtonAction:(id)sender {

    _mapView.showsUserLocation = NO;
    if (_txtQueryKey.text == nil || _txtQueryKey.text.length == 0) {
        return;
    }
     //地理信息编码查询
    CLGeocoder *geocder = [[CLGeocoder alloc] init];
   [geocder geocodeAddressString:_txtQueryKey.text completionHandler:^(NSArray *placemarks, NSError *error) {

       if (placemarks.count > 0){
            CLPlacemark *placemark = placemarks[0];
            newLocation = placemark.location;
            toCoordinate = CLLocationCoordinate2DMake(placemark.location.coordinate.latitude,placemark.location.coordinate.longitude);
           //调整地图位置和缩放比例
           //第一个参数指定目标区域的中心点,第二个参数是目标区域的南北跨度,单位为米。第三个参数为目标区域东西跨度,单位为米。后2个参数的调整会影响地图的缩放
            MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(placemark.location.coordinate, 600, 600);
            //重新设置地图视图的显示区域
            [_mapView setRegion:viewRegion animated:YES];
            //实例化MyAnnotation对象
            MyAnnotation *annotation = [[MyAnnotation alloc] init];
            //将地标CLPlacemark对象取出,放入到MyAnnotation对象中
            annotation.myTitle = placemark.locality;
            annotation.mySubtitle = [NSString stringWithFormat:@"%@, %@, %@",placemark.locality,placemark.administrativeArea,placemark.thoroughfare];
           annotation.coordinate = placemark.location.coordinate;

            //把标注点MyAnnotation对象添加到地图上
            [_mapView addAnnotation:annotation];
           //关闭键盘
           [_txtQueryKey resignFirstResponder];
        }

    }];

}



//在地图视图添加标注时回调
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(MyAnnotation *)annotation
{
    MKPinAnnotationView *ann = (MKPinAnnotationView *)[_mapView dequeueReusableAnnotationViewWithIdentifier:@"ID"];
    if (ann == nil) {
        ann = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"ID"];
    }
    ann.pinColor = MKPinAnnotationColorPurple;
    ann.animatesDrop = YES;
    ann.canShowCallout = YES;

    return ann;
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [locationManager requestWhenInUseAuthorization];
            }
            break;        
        default:            
            break;   
    }
}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值