본문 바로가기
프로그래밍/iOS

맵뷰(MapView) 5장 - 한점과 나의 거리는?? (getDistanceFrom:)

by 백룡화검 2012. 2. 9.

결과물입니다.




 

=====================================================================================

.h에서 거리를 위한 변수하나를 잡아줍니다.


 
 @interface testLocationViewController : UIViewController <CLLocationManagerDelegate> {
   
    CLLocationManager *locationManager;
    CLLocation *startPoint;
   
    MKMapView *myMapView;
   
    NSMutableArray *arrayLatitude;
    NSMutableArray *arrayLongitude;
   
    NSMutableArray *distance;
}

@property (nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, retain) CLLocation *startPoint;
@property (nonatomic, retain) NSMutableArray *arrayLatitude;
@property (nonatomic, retain) NSMutableArray *arrayLongitude;
@property (nonatomic, retain) NSMutableArray *distance;


- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation;

//- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;

@end


==========================================================================================


.m으로 갑니다.


원래 어디까지 구현을할지 기획이 안되있던상태라 구현부분에 변화가 있습니다.

핀이 꼽힐때 위치를 먼저 계산한 상태여야 subtitle에 거리가 들아갈수 있습니다.

그래서  - (id) init 에 있던 핀을 꼽아주던 부분의 위치를 - (void)locationManager 안으로 이동해줍니다.

locationManager가 시작되야 현재위치를 잡아주고 거리를 계산할수 있기 때문이죠.

물론 MKMapView에서 setShowsUserLocation을 YES로 설정했기때문에 locationManager를 사용하지 않고도 가능합니다만, locationManager를 써보려고 하는거니까 안으로 옮겨줄께요.


그리고 .h에서 만들고 @property로 쏴준 NSMutableArray *distance@synthesize distance로 받아줘야겠죠.


거리를 계산하는 함수는 CLLocationDistance입니다.

레퍼런스를 확인하시면 아시겠지만 [A distanceFromLocation:B]으로 A와 B와의 거리를 계산해줍니다.

3.2버전 이전에는 [A getDistanceFrom:B]였습니다.

CLLocationDistance simple = [A distanceFromLocation:B];면 되겠네요.


#import "testLocationViewController.h"

@implementation testLocationViewController
@synthesize locationManager, startPoint;
@synthesize arrayLatitude, arrayLongitude;

@synthesize distance;

- (id) init {
    self = [super init];
    if (self != nil) {
        myMapView = [[MKMapView alloc] initWithFrame:CGRectMake(0.0, 20.0, 320.0, 460.0)];
        [myMapView setShowsUserLocation:YES];
        [myMapView setMapType:MKMapTypeStandard];
        [myMapView .userLocation setTitle:@"Here I am"];
        [self.view insertSubview:myMapView atIndex:0];
        
        locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        locationManager.distanceFilter = kCLDistanceFilterNone;
        [locationManager startUpdatingLocation];
        
        float rLatitude;
        float rLongitude;
        arrayLatitude = [[NSMutableArray alloc] init];
        arrayLongitude = [[NSMutableArray alloc] init];

        for (int i = 0 ; i < 10; i ++) {
            int a = rand();
            NSLog(@"A:%d",a);
            
            rLatitude = ((rand()%(376655427-376529902) + 376529902) * 0.0000001);
            rLongitude = ((rand()%(1267663371-1267552399) + 1267552399) * 0.0000001);
            
            NSNumber *temLatitude = [NSNumber numberWithFloat:rLatitude];
            NSNumber *temrLongitude = [NSNumber numberWithFloat:rLongitude];
            [arrayLatitude addObject:temLatitude];
            [arrayLongitude addObject:temrLongitude];
        }
        for (int i = 0; i < 10; i++) {
            NSLog(@"rLatitude : %f", [[arrayLatitude objectAtIndex:i] floatValue]);
            NSLog(@"arrayLongitude : %f", [[arrayLongitude objectAtIndex:i] floatValue]);
        }
    }
    return self;
}


- (void)locationManager:(CLLocationManager *)manager
     didUpdateToLocation:(CLLocation *)newLocation
                 fromLocation:(CLLocation *)oldLocation {

    if (startPoint == nil) {
        self.startPoint = newLocation;
    }
    
    NSLog(@"Location: %@", [newLocation description]);
    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 100, 100);
    [myMapView setRegion:viewRegion animated:YES];


    //거리계산
    distance = [[NSMutableArray alloc] init];
    for (int i = 0; i < [arrayLatitude count]; i++) {
        CLLocation *loc = [[CLLocation alloc] initWithLatitude:[[arrayLatitude objectAtIndex:i]doubleValue]
                                                     longitude:[[arrayLongitude objectAtIndex:i] doubleValue]];
        CLLocationDistance smDista = [newLocation distanceFromLocation:loc];
        NSString *disString = [[NSString alloc] initWithFormat:@"%f", smDista];
        NSLog(@"%d : %@", i, disString);
        [distance addObject:disString];
    }


    //핀을 꼽아줍니다.

    for (int i = 0; i < [arrayLatitude count] ; i++) {
        Pin *ann = [[Pin alloc] init];
        ann.title = [NSString stringWithFormat:@"좌표 %d", i];

        ann.subtitle = [NSString stringWithFormat:@"거리 : %dM", (int)[[distance objectAtIndex:i] floatValue]];
        CLLocationCoordinate2D center;
        center.latitude = [[arrayLatitude objectAtIndex:i] doubleValue];
        center.longitude = [[arrayLongitude objectAtIndex:i] doubleValue];
        ann.coordinate = center;
        [myMapView addAnnotation:ann];
    }


    [locationManager stopUpdatingLocation];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    self.locationManager = nil;
    self.startPoint = nil;
}


- (void)dealloc {
    [locationManager release];
    [startPoint release];
    [super dealloc];
}

@end

==========================================================================================
distance = [[NSMutableArray alloc] init]

distance를 초기화시켜줍니다. 이제 모르시는 분은 안계시겠지요?


for (int i = 0; i < [arrayLatitude count]; i++) {

일반적인 포문입니다. arrayLatitude의 갯수만큼 돌려줍니다.


CLLocation *loc = [[CLLocation alloc] initWithLatitude:[[arrayLatitude objectAtIndex:i] doubleValue]
                                                     longitude:[[arrayLongitude objectAtIndex:i] doubleValue]];

CLLocation형식으로 x, y좌표를 넣어줍니다.


CLLocationDistance smDista = [newLocation distanceFromLocation:loc];

거리를 계산하고,


NSString *disString = [[NSString alloc] initWithFormat:@"%f", smDista];

계산된 거리를 NSString에 넣어줍니다. 바로 subtitle나 로그로 찍으려고하면 안나옵니다.


NSLog(@"%d : %@", i, disString);

로그로 찍고,


[distance addObject:disString];

배열인 distance에 차례대로 넣어줍니다.

}


끗!!