iOS8 地图的使用

在iOS8 中, 若使用系统自带的地图, 首先在Plist文件中添加两个字段 : NSLocationAlwaysUsageDescription 和 NSLocationWhenInUseUsageDescription 类型均为String类型 其次要注意 : Supported interface orientations 是否存在 不存在则创建 (Array类型);

使用地图首先引入MapKit库 之后必要的一个代理<CLLocationManagerDelegate>

@interface ViewController ()<CLLocationManagerDelegate>

@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLLocation *nameLocation;

@end

  

创建地图:

self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 140, self.view.frame.size.width, self.view.frame.size.height - 140)];
    
    self.mapView.showsUserLocation = YES; // 定位到自己的位置
    //self.mapView.mapType = MKMapTypeSatellite; // 地图类型 这里是卫星 具体地图类型请查看API
    
    [self.view addSubview:self.mapView];
    
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest; //控制定位精度,越高耗电量越大。
    
    _locationManager.distanceFilter = 10; //控制定位服务更新频率。单位是“米”
  [self.locationManager startUpdatingLocation];

  

在iOS8中 可能会不弹出是否允许使用地理位置的AlertView, 需要处理一下

if([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [_locationManager requestWhenInUseAuthorization];
   }

// 判断服务是否开启
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    if (
        ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)] && status != kCLAuthorizationStatusNotDetermined && status != kCLAuthorizationStatusAuthorizedWhenInUse) ||
        (![_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)] && status != kCLAuthorizationStatusNotDetermined && status != kCLAuthorizationStatusAuthorized)
        ) {
        
        NSString *message = @"您的手机目前未开启定位服务,如欲开启定位服务,请至设定开启定位服务功能";
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"无法定位" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        
    }else {
        
        [_locationManager startUpdatingLocation];
    }
}

  

创建一个大头针类 : CustomAnnotation 继承于NSObject

//
//  CustomAnnotation.h
//  Map
//
//  Created by 高岐 on 15/4/6.
//  Copyright (c) 2015年 GaoQi. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface CustomAnnotation : NSObject<MKAnnotation>
{
    CLLocationCoordinate2D coordinate;
    NSString *title;
    NSString *subtitle;
}
-(id) initWithCoordinate:(CLLocationCoordinate2D) coords;

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;

@end

  

//
//  CustomAnnotation.m
//  Map
//
//  Created by 高岐 on 15/4/6.
//  Copyright (c) 2015年 GaoQi. All rights reserved.
//

#import "CustomAnnotation.h"

@implementation CustomAnnotation
@synthesize coordinate, title, subtitle;

-(id) initWithCoordinate:(CLLocationCoordinate2D) coords
{
    if (self = [super init]) {
        coordinate = coords;
    }
    return self;
}
@end

  

// 添加大头针
-(void)createAnnotationWithCoords:(CLLocationCoordinate2D) coords {
    CustomAnnotation *annotation = [[CustomAnnotation alloc] initWithCoordinate:
                                    coords];
   // 通过self.nameLocation 点击大头针得到具体街道地址
    CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
    [clGeoCoder reverseGeocodeLocation:self.nameLocation completionHandler: ^(NSArray *placemarks,NSError *error) {
        
        for (CLPlacemark *placeMark in placemarks)
        {
            NSDictionary *addressDic=placeMark.addressDictionary;
            
            NSString *state=[addressDic objectForKey:@"State"];
            NSString *city=[addressDic objectForKey:@"City"];
            NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
            NSString *street=[addressDic objectForKey:@"Street"];
            
            annotation.title = [NSString stringWithFormat:@"%@%@%@%@", state, city, subLocality, street]; // 点击大头针得到具体街道地址

        }
        
    }];

    
    
    [self.mapView addAnnotation:annotation];
}

  

接下来就是定位了

// 通过城市名字用大头针定位, 这是通过一个button 和一个 textField(self.text) 来进行搜索的 以下是button 的点击方法 实际上是先定位 在放置大头针的(只能定位在国内)
- (void)buttonClick
{
    // 通过大头针定位在故宫
//    CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(39.915352,116.397105);
//    float zoomLevel = 0.02;
//    MKCoordinateRegion region = MKCoordinateRegionMake(coords, MKCoordinateSpanMake(zoomLevel, zoomLevel));
//    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
//    
//    
//    [self createAnnotationWithCoords:coords];
    
    // 通过名字获取地理位置 并用大头针定位
    CLGeocoder *myGeocoder = [[CLGeocoder alloc] init];
    [myGeocoder geocodeAddressString:self.text.text completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([placemarks count] > 0 && error == nil)
        {
           // NSLog(@"Found %lu placemark(s).", (unsigned long)[placemarks count]);
            CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
            //NSLog(@"Longitude = %f", firstPlacemark.location.coordinate.longitude);
            //NSLog(@"Latitude = %f", firstPlacemark.location.coordinate.latitude);
            
            // 通过经纬度得到地理信息(省,市,区,街道) 传回到大头针哪里 然后大头针定位
            self.nameLocation = [[CLLocation alloc] initWithLatitude:firstPlacemark.location.coordinate.latitude longitude:firstPlacemark.location.coordinate.longitude];
            
            // P.S.这个地方我也不知道写的对不对 (是点击搜索button会缓冲一段时间的问题 不是定位问题 网络慢?)
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(firstPlacemark.location.coordinate.latitude,firstPlacemark.location.coordinate.longitude);
                float zoomLevel = 0.02;

               MKCoordinateRegion region = MKCoordinateRegionMake(coords, MKCoordinateSpanMake(zoomLevel, zoomLevel));
                [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES]; // 移动到定位的位置
                
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [self createAnnotationWithCoords:coords];

                    
                });
                
                
            });
            
        }
        else if ([placemarks count] == 0 && error == nil)
        {
            NSLog(@"Found no placemarks.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];

}

  

还有一些代理方法之类的

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    // 代理方法打印经纬度
    [self.locationManager stopUpdatingLocation];
    
    NSString *strLat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];
    NSString *strLng = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];
    NSLog(@"Lat: %@  Lng: %@", strLat, strLng);
    
    // 地图移动到当前位置
    
    CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(newLocation.coordinate.latitude,newLocation.coordinate.longitude);
    float zoomLevel = 0.02;
    MKCoordinateRegion region = MKCoordinateRegionMake(coords,MKCoordinateSpanMake(zoomLevel, zoomLevel));
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
    

    
}
// 错误报告
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"locError:%@", error);
    
}

  

 

posted @ 2015-04-12 13:41  Mr.Greg  阅读(257)  评论(0编辑  收藏  举报