Core Location


In this post we will have a look at the core location framework

Core location description: The core location framework determines the current location associated with the device. You have to use the delegates and protocols associated with this class in order to show the users current location. You can also use this framework to define a geographic region and monitor when the user crosses the boundaries of those regions.

Design phase: In this app we will just determine the users current location (latitude and longitude) and supply those latitude and longitude to the map kit so that the user can see where he/she is.

For this we need two objects of UITextField, one object of MKMapView and two objects of UILabel and here’s a view at our final output

Step 1: Open Xcode and create a window based application, add a UIViewController subclass file into your application and name it myviewController, now you their will be two files added into your class group one with the name myviewController.h and other with the name myviewController.m. Before preceding any further it would be nice if we add the MapKit and Core location framework into our project (Refer this link if you forgot how to add a framework).

Step 2: Select the myviewController.h file and declare the objects of  class MKMapView, UILabel and UITextFields of course we will require two variable of double type where we will store the new location of the user. Also add a class called CLLocationManager which we will use to determine the users current location. Here’s a view at the code in the myviewController.h file

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h> 
#import <MapKit/MapKit.h>
@interface myviewController : UIViewController <CLLocationManagerDelegate> {

MKMapView *mymapView;
UILabel *latitudeLabel,*longitudeLabel;
UITextField *lat,*longi;
double usersLatitude,usersLongitude;
CLLocationManager *mylocationManager;
}
@end


Don't forget to import the map kit and the core location framework and to use the CLLocationManagerDelegate protocol. 

CLLocationManager Description: You use an instance of this class to establish the parameters that determine when location and heading events should be delivered. You can also use a location manager object to retrieve the most recent location data.

Step 3: Select the myviewController.m file and allocate memory for the labels and text fields.
Into the loadView method allocate memory for the MKMapVIew object and add all the views to the self view.

init method code

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
//setting the labels
latitudeLabel = [[UILabel alloc]initWithFrame:CGRectMake(16, 66, 66, 21)];
latitudeLabel.text = @"Latitude:";
longitudeLabel = [[UILabel alloc]initWithFrame:CGRectMake(16, 105, 80, 21)];
longitudeLabel.text = @"Longitude:";

//setting the text fields
lat = [[UITextField alloc]initWithFrame:CGRectMake(123, 63, 97, 31)];
[lat setBorderStyle:UITextBorderStyleRoundedRect];
lat.userInteractionEnabled = NO;
longi = [[UITextField alloc]initWithFrame:CGRectMake(123, 102, 97, 31)];
[longi setBorderStyle:UITextBorderStyleRoundedRect];
longi.userInteractionEnabled = NO;


//settings for the CLLocationManager class
mylocationManager = [[CLLocationManager alloc]init];
[mylocationManager startUpdatingLocation];
mylocationManager.delegate = self;

    }
    return self;
}

The loadView method

-(void) loadView
{
[super loadView];
[self.view addSubview:latitudeLabel];
[self.view addSubview:longitudeLabel];
[self.view addSubview:lat];
[self.view addSubview:longi];
mymapView = [[MKMapView alloc]initWithFrame:CGRectMake(16, 151, 284, 266)];
mymapView.mapType = MKMapTypeStandard;
[self.view addSubview:mymapView];
}




Step 4: CLLocationManager has a protocol method called locationManagerDidUpdateToLocation this method will provide you with the old location from where you were and the new location to where you are, use this method to get the latitude and longitude of you new location and supply those to the map view so that the map view can display your current location.

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
lat.text = [NSString stringWithFormat:@"%lf",newLocation.coordinate.latitude];
longi.text = [NSString stringWithFormat:@"%lf",newLocation.coordinate.longitude];
usersLatitude = newLocation.coordinate.latitude;
usersLongitude = newLocation.coordinate.longitude;
CLLocationCoordinate2D cord = {usersLatitude,usersLongitude};
MKCoordinateSpan span = {0.3,0.3};
MKCoordinateRegion  reg = {cord,span};
mymapView.showsUserLocation = YES;
[mymapView setRegion:reg];
}


Step 5: Select the AppDelegate.m file in your project and add code to add the self view to your iPhone simulator and run the application

#import "coreLocationAppDelegate.h"
#import "myviewController.h"

@implementation coreLocationAppDelegate
@synthesize window;
#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
    // Override point for customization after application launch.
myviewController *obj = [[myviewController alloc]init];
[window addSubview:obj.view];
        [window makeKeyAndVisible];
    return YES;
}



It would be better if you deploy this app into the device and then run it for better results


Some extra stuff:

The above method by which I have showed you the demonstration of core location will always update the user about his current location.
Now this method is useful but has a defect and that’s it consumes lots of memory which is not a good sign,
But not to worry in the documentation for CLLocationManager there is another method to show the user his/her current location and that method is

-   (void)startMonitoringSignificantLocationChanges

The above method will only update the users location based upon significant location changes.

I hope this post has helped you, Happy iCoding and have a nice day

Comments

  1. Thank you sir......it really helps me.......
    have gud day

    ReplyDelete
  2. Good information! Thanks for post!

    ReplyDelete
  3. @Radix: hello thanx for giving such information i use this code but it shows my current location in San Fransisco.. but i m in india.. so how can i change my location...!!!

    ReplyDelete
  4. @jayraj: its the default location of iPhone, are you testing it inside the simulator then thats not a good thing to do,

    You have to deploy the app into your device to see your current location in lat/long form here's a link to my blog to deploy an app in the device

    http://iphonebyradix.blogspot.in/2011/07/installing-app-to-iphone-device.html

    ReplyDelete
  5. @Radix: Thank you for your reply and great support i will try to deploy application on my mobile and then check it.. then i will tell you what happen..!!
    regards
    jayraj

    ReplyDelete
  6. @jayraj: looking forward to it :)

    ReplyDelete

Post a Comment