iOS 개발 에서 가장 기본 적 인 위치 기능 구현 예시

15271 단어 iOS
포 지 셔 닝 가 져 오기 위치 및 위치 인 코딩-역 인 코딩
저희 프로그램 은 Core Location 프레임 워 크 에 포 함 된 클래스 를 추가 하여 장치 의 지도 위 치 를 가 져 올 수 있 습 니 다.
CoreLocation.framework 프레임 워 크 를 추가 하고\#import를 가 져 옵 니 다.
지도 서 비 스 를 사용 할 때 더 많은 설비 의 전 기 를 소모 할 수 있 습 니 다.따라서 설비 의 위 치 를 얻 은 후에 포 지 셔 닝 을 중단 하여 전 기 를 절약 해 야 합 니 다.
우 리 는 하나의 demo 를 통 해 내용 과 효 과 를 보 여 준다.

//
// HMTRootViewController.h
// My-GPS-Map
//
// Created by hmt on 14-4-12.
// Copyright (c) 2014 . All rights reserved.
//

#import <UIKit/UIKit.h>

@interface HMTRootViewController : UIViewController <CLLocationManagerDelegate>

@end

//
// HMTRootViewController.m
// My-GPS-Map
//
// Created by hmt on 14-4-12.
// Copyright (c) 2014 . All rights reserved.
//

#import "HMTRootViewController.h"
#import <AddressBook/AddressBook.h>

@interface HMTRootViewController (){

CLLocationManager * _locationManage;
}

@property (nonatomic,retain) CLLocationManager * locationManage;

@end

@implementation HMTRootViewController

- (void)dealloc{

RELEASE_SAFELY(_locationManage);
[super dealloc];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.

[self createGPSMap];
self.view.backgroundColor = [UIColor redColor];

}

- (void)createGPSMap{

//
self.locationManage = [[CLLocationManager alloc]init];

// CLLocationManager
_locationManage.distanceFilter = kCLDistanceFilterNone;

//
_locationManage.desiredAccuracy = kCLLocationAccuracyBest;

//
_locationManage.delegate = self;

//
[_locationManage startUpdatingLocation];

[_locationManage release];

}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{

CLLocation * newLocation = [locations lastObject];
//
[_locationManage stopUpdatingLocation];

//
CLLocationCoordinate2D coord2D = newLocation.coordinate;
double latitude = coord2D.latitude;
double longitude = coord2D.longitude;
NSLog(@" = %f = %f",latitude,longitude);

//
CLLocationAccuracy horizontal = newLocation.horizontalAccuracy;
CLLocationAccuracy vertical = newLocation.verticalAccuracy;
NSLog(@" = %f = %f",horizontal,vertical);

//
CLLocationDistance altitude = newLocation.altitude;
NSLog(@"%f",altitude);

//
NSDate *timestamp = [newLocation timestamp];
// NSDateFormatter
NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
//
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss a"];
[dateFormat setAMSymbol:@"AM"]; // , " "
[dateFormat setPMSymbol:@"PM"];
// , ,
NSString *dateString = [dateFormat stringFromDate:timestamp];
NSLog(@" = %@",dateString);


// ----------------------------------------- --------------------------------------------
CLGeocoder * geocoder = [[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {

for (CLPlacemark * place in placemarks) {

NSLog(@"name = %@",place.name); //
NSLog(@"thoroughfare = %@",place.thoroughfare); //
NSLog(@"subAdministrativeArea = %@",place.subAdministrativeArea); //
NSLog(@"locality = %@",place.locality); //
NSLog(@"subLocality = %@",place.subLocality); //
NSLog(@"country = %@",place.country); //

NSArray *allKeys = place.addressDictionary.allKeys;
for (NSString *key in allKeys)
{
NSLog(@"key = %@, value = %@",key, place.addressDictionary[key]);
}
#pragma mark - , AddressBook
NSLog(@"kABPersonAddressCityKey = %@", (NSString *)kABPersonAddressCityKey);
NSLog(@"city = %@", place.addressDictionary[(NSString *)kABPersonAddressCityKey]);
NSString *city = place.locality;
if(city == nil)
{
city = place.addressDictionary[(NSString *)kABPersonAddressStateKey];
}
}
}];
}


- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end
프로그램 실행 결과:(39.3,116.4 를 예 로 들 면)

//   
if (self.locationTextField.text == nil  ||  [self.locationTextField.text length] == 0) { 
    return; 

 
CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 
/*  ----------------------------------------- --------------------------------------------  */ 
[geocoder geocodeAddressString:_locationTextField.text completionHandler:^(NSArray *placemarks, NSError *error) { 
     
    for (CLPlacemark *placemark in placemarks) { 
         
        CLLocationCoordinate2D coordinate = placemark.location.coordinate; 
        NSString *strCoordinate = [NSString stringWithFormat:@" = %3.5f
= %3.5f",coordinate.latitude,coordinate.longitude]; 
        NSLog(@"%@",strCoordinate); 
        NSDictionary *addressDictionary = placemark.addressDictionary; 
        NSString *address = [addressDictionary objectForKey:(NSString *)kABPersonAddressStreetKey]; 
        NSString *state = [addressDictionary objectForKey:(NSString *)kABPersonAddressStateKey]; 
        NSString *city = [addressDictionary objectForKey:(NSString *)kABPersonAddressCityKey]; 
        NSLog(@" = %@
= %@
= %@",address,state,city); 
    } 
}]; 
지도 사용 및 표시 지도
CoreLocation 프레임 워 크 를 사용 하여 현재 장치 의 위 치 를 가 져 왔 습 니 다.이 장 은 지도 사용 을 소개 합 니 다.
우선,프레임 워 크 가 져 오기:

#import <MapKit/MapKit.h>
main 코드 예제

main.h 
 
#import <UIKit/UIKit.h> 
#import <MapKit/MapKit.h> 
//   
@interface HMTMainViewController : UIViewController<MKMapViewDelegate> 
 
@end 
 
main.m 
 
// 
//  HMTMainViewController.m 
//  Map 
// 
//  Created by HMT on 14-6-21. 
//  Copyright (c) 2014 humingtao. All rights reserved. 
// 
 
#import "HMTMainViewController.h" 
#import "HMTAnnotation.h" 
 
@interface HMTMainViewController () 
 
@property (nonatomic ,strong) MKMapView *mapView; 
 
@end 
 
@implementation HMTMainViewController 
 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
        // Custom initialization 
    } 
    return self; 

 
- (void)viewDidLoad 
 

     
    [super viewDidLoad]; 
    self.view.backgroundColor = [UIColor redColor]; 
     
    // Do any additional setup after loading the view. 
     
    self.navigationItem.title = @" "; 
    self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)]; 
     
    //   
    self.mapView.showsUserLocation = YES; 
    //   
    self.mapView.delegate = self; 
     
    //   
    /**
     *      MKMapTypeStandard = 0, // 
     *      MKMapTypeSatellite,    // 
     *      MKMapTypeHybrid        // 
     */ 
    self.mapView.mapType = MKMapTypeStandard; 
    //   
    CLLocationCoordinate2D coord2D = {39.910650,116.47030}; 
    //  , ,  
    MKCoordinateSpan span = {0.1,0.1}; 
    //   
    MKCoordinateRegion region = {coord2D,span}; 
    //   
    [self.mapView setRegion:region animated:YES]; 
    //   
    //self.mapView.zoomEnabled = NO; 
    //   
    //self.mapView.scrollEnabled = NO; 
 
    //  Annotation( ) 
    HMTAnnotation *annotation = [[HMTAnnotation alloc] initWithCGLocation:coord2D]; 
    //   
    annotation.title = @" "; 
    //   
    annotation.subtitle = @" "; 
    //  ( , viewForAnnotation) 
    [self.mapView addAnnotation:annotation]; 
     
    [self.view addSubview:_mapView]; 
     

 
//   ( ) 
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{ 
 
    /**
     *  UITableViewCell
     */ 
    static NSString *identifier = @"annotation"; 
    //  (MKPinAnnotationView , MKAnnotation) 
    MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier]; 
    if (annotationView == nil) { 
        annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier]; 
    } 
    //   
    if ([annotation isKindOfClass:[HMTAnnotation class]]) { 
         
        //   
        annotationView.pinColor = MKPinAnnotationColorGreen; 
        //   
        annotationView.canShowCallout = YES; 
        //  , MKAnnotationView;MKPinAnnotationView !!!! 
        annotationView.image = [UIImage imageNamed:@"customImage"]; 
        //  ( , API) 
        UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; 
        [button addTarget:self action:@selector(didClickAnnotationViewRightButtonAction:) forControlEvents:UIControlEventTouchUpInside]; 
        annotationView.rightCalloutAccessoryView = button; 
        //  ( ) 
        annotationView.animatesDrop = YES; 
        annotationView.annotation = annotation; 
         
        //   
        return annotationView; 
         
    }else{ 
        
        //  , nil,  
        return nil; 
    } 
     

 
- (void)didClickAnnotationViewRightButtonAction:(UIButton *)button{ 
 
    NSLog(@"%d %s",__LINE__,__FUNCTION__); 

 
//   
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{ 
 
    NSLog(@"%d %s",__LINE__,__FUNCTION__); 

 
//   
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{ 
     
    NSLog(@"%d %s",__LINE__,__FUNCTION__); 

 
//   
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{ 
 
    NSLog(@"%d %s",__LINE__,__FUNCTION__); 

 
- (void)didReceiveMemoryWarning 

    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 

 
@end 
사용자 정의 MKAnnotationView

#import <Foundation/Foundation.h> 
#import <MapKit/MapKit.h> 
//  MKAnnotation , !!!!!!!!! 
@interface HMTAnnotation : NSObject<MKAnnotation> 
 
@property (nonatomic,readonly) CLLocationCoordinate2D coordinate;  //   
@property (nonatomic,copy) NSString *title;     //   
@property (nonatomic,copy) NSString *subtitle;  //  ( ) 
 
- (id)initWithCGLocation:(CLLocationCoordinate2D) coordinate; 
 
@end 
 
#import "HMTAnnotation.h" 
 
@implementation HMTAnnotation 
 
- (id)initWithCGLocation:(CLLocationCoordinate2D)coordinate{ 
 
    if (self = [super init]) { 
         
        _coordinate = coordinate; 
    } 
    return self; 

 
@end 
효과 그림:

좋은 웹페이지 즐겨찾기