Friday, 30 March 2012

GPS Location in iPhone

Make a config file and put there

// Name : Config.h >
// Add this line at import section
#import <CoreLocation/CoreLocation.h>



//Add this to instance section / property section 
//for GPS current location
extern float core_latitude, core_longitude;

extern CLLocationManager    *locationManager;         //
extern CLLocation           *currentLocation;        // For Latitude & Longitude
extern CLLocationCoordinate2D coordinates;          //
 -------------------------------------
// Name : Config.m >

// Add this code
// for GPS current location
float core_latitude = 0.0f, core_longitude = 0.0f;

CLLocationManager *locationManager;                            //
CLLocation *currentLocation;                                // For Latitude & Longitude
CLLocationCoordinate2D coordinates;                            //

============================
// Name : AppDelegate.h >

1.  Add    #import <CoreLocation/CoreLocation.h> Class to file
 2. Add   <CLLocationManagerDelegate> protocol to file


// Name : AppDelegate.m >


1.   Add this code into
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{}

>>>

//for GPS current location
    //for getting Lattitude & Longitude
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    [locationManager startUpdatingLocation];


2 . Write this code into AppDelegate.m file //implement the protocol CLLocationManagerDelegate

#pragma mark - GPS current location
#pragma mark CLLocation methods

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    //if the time interval returned from core location is more than two minutes we ignore it because it might be from an old session
    if ( abs([newLocation.timestamp timeIntervalSinceDate: [NSDate date]]) < 120) {            
        //CLLocation *test = [[CLLocation alloc] initWithLatitude:-33.857034 longitude:151.035929];
        currentLocation = newLocation;
        coordinates = newLocation.coordinate;
       
        core_latitude = currentLocation.coordinate.latitude;
        core_longitude = currentLocation.coordinate.longitude;
       
        [locationManager stopUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
   
    //latitude = 43.795365;
    // longitude = -79.183776;
    NSLog(@"%@", [error description]);
   
}
=====================
core_latitude, core_longitude which defined as extern in Config file is automatic updated in background and this is the right GPS location.
Use core_latitude, core_longitude for current location in anywhere

No comments:

Post a Comment