This article explains how to get the current location in iPhone programming. Import the CoreLocation API in the iPhone application and use the following code
// MyCLController.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@protocol MyCLControllerDelegate
@required
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
@end
@interface MyCLController : NSObject <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
id delegate;
}
@property (nonatomic, retain) CLLocationManager *locationManager; @property (nonatomic, assign) id delegate;
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation;
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error;
@end
// MyCLController.m
#import "MyCLController.h"
@implementation MyCLController
@synthesize locationManager;
@synthesize delegate;
- (id) init {
self = [super init];
if (self != nil) {
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
[self.delegate locationUpdate:newLocation];
[locationManager stopUpdatingLocation]; }
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
[self.delegate locationError:error];
}
- (void)dealloc {
[self.locationManager release];
[super dealloc];
}
@end
// Use the follwing code to get the current location latitude and longitude
- (void)viewDidLoad {
[self setTitle:contactLocation];
locationController = [[MyCLController alloc] init];
locationController.delegate = self;
[locationController.locationManager startUpdatingLocation];
[super viewDidLoad];
}
- (void)locationUpdate:(CLLocation *)location {
CLLocationCoordinate2D currentLocation = location.coordinate;
latitude = currentLocation.latitude;
longitude = currentLocation.longitude;
}
- (void)locationError:(NSError *)error {
NSLog(@"Location Error Occured");
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment