The following tutorial explains the use of Core Location Framework from iOS 5.
This application demonstrates use of
1) Core Location to track the location of the iphone
2) Map kit to visualize the location of the iphone
3) It places waypoint
s on the map after every 10 seconds and
4) Joins those waypoints using a black colored line.
Note : It is suggested to try out the application on the actual device as you cannot simulate location changes on the simulator
The Screenshots below explain how to
1) Create an xcode project using Xcode 4
2) Adding frameworks to the project (Mapkit and Core Location Framework)
3) Adding Delegates (MKMapViewDelegate, CLLocationManagerDelegate, UITextFieldDelegate)
4) Adding the basic UI elements using Interface builder
After this, I have included the header file which contains the properties and IBOutlets for the interface elements.
// iosViewController.h // Tracker // Created by Pratik Hande. // Copyright (c) 2012. All rights reserved. #import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h> #import <MapKit/MapKit.h> @interface iosViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate, UITextFieldDelegate>{ // IBOutlets for the results of core location updates to be displayed IBOutlet UITextField *latitudeLongitude; IBOutlet UITextField *time; IBOutlet UITextField *speed; IBOutlet UITextField *distance; // Core Location Manager for managing location updates CLLocationManager *locationManager; // Map View for displaying results to a map IBOutlet MKMapView *map; // An array of way points where pins would be dropped on the map NSMutableArray *wayPoints; // Timer elements for timing location updates NSTimer *stopTimer; NSDate *stopTime; NSDate *startTime; // Total distance form the starting location float totalDistance; // Location instances to save inetermediate locations CLLocation *tempNewLocation, *tempOldLocation; // To draw the connecting line between waypoints MKPolyline * routeLine; } @property(nonatomic,retain) IBOutlet UITextField *latitudeLongitude; @property(nonatomic,retain) IBOutlet UITextField *time; @property(nonatomic,retain) IBOutlet UITextField *speed; @property(nonatomic,retain) IBOutlet UITextField *distance; @property(nonatomic, retain) CLLocationManager *locationManager; @property(nonatomic, retain) IBOutlet MKMapView *map; @property(nonatomic, retain) MKPolyline *routeLine; @endImplementation explained
In viewDidLoad()
1) We first create an instance of CLLocationManager and provide a delegate for it which is self. 2) We set the desiredAccuracy to 6.0 which indicates the accuracy desired on location horizontally.
3) We set the distanceFilter, which indicates the distance change after which a location update is received.
4) We call startUpdatingLocation method to start receiving location updates.
5) We assign a delegate for map view to self.
6) The setShowsUserLocation:YES shows a blue marker on the map view indicating the current location.
7) The call to setUserTrackingMode:MKUserTrackingModeFollow animated:YES allows the tracking of location on the map in an animated manner.
8) We also initialize an array for waypoints which would hold the locations on the map which have been marked.
9) Next we create, stop timer for based on a 10 second interval.// iosViewController.m // Tracker // Created by Pratik Hande. // Copyright (c) 2012. All rights reserved. // #import "iosViewController.h" @implementation iosViewController @synthesize latitudeLongitude, time, speed, distance, locationManager, map, routeLine; - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.desiredAccuracy = 6.0; locationManager.distanceFilter = 6.0; [locationManager startUpdatingLocation ]; map.delegate = self; [map setShowsUserLocation:YES]; [map setUserTrackingMode:MKUserTrackingModeFollow animated:YES]; wayPoints = [[NSMutableArray alloc] initWithCapacity:30]; totalDistance = 0.0; stopTime = [NSDate dateWithTimeIntervalSinceNow:140]; startTime = [NSDate date]; SEL sel = @selector(timerTargetMethod); NSInvocation* inv = [NSInvocation invocationWithMethodSignature: [self methodSignatureForSelector:sel]]; [inv setTarget:self]; [inv setSelector:sel]; stopTimer = [NSTimer scheduledTimerWithTimeInterval:10 invocation:inv repeats:true]; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { if(newLocation != nil && oldLocation != newLocation) { tempNewLocation = newLocation; tempOldLocation = oldLocation; } } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { } - (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views { MKAnnotationView *annotationView = [views objectAtIndex:0]; id mp = [annotationView annotation]; MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,250,250); [mv setRegion:region animated:YES]; } // MKMapViewDelegate - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id )overlay { MKOverlayView* overlayView = nil; MKPolylineView * routeLineView = [[MKPolylineView alloc] initWithPolyline:self.routeLine]; routeLineView.fillColor = [UIColor colorWithRed:0.0-1.0 green:0.0-1.0 blue:0.0-1.0 alpha:1.0f]; routeLineView.strokeColor = [UIColor colorWithRed:0.0-1.0 green:0.0-1.0 blue:0.0-1.0 alpha:1.0f]; routeLineView.lineWidth = 10; routeLineView.lineCap = kCGLineCapSquare; overlayView = routeLineView; return overlayView; } //define the targetmethod -(void) timerTargetMethod { if([[NSDate date] timeIntervalSinceDate:startTime] >= 140) { [stopTimer invalidate]; [locationManager stopUpdatingLocation]; NSLog(@"Time started at %@", startTime); NSLog(@"Time up at %@", stopTime); } else if (tempOldLocation.coordinate.latitude == tempNewLocation.coordinate.latitude && tempNewLocation.coordinate.longitude == tempOldLocation.coordinate.longitude) { NSLog(@" Fix location found "); } else if( [[NSDate date] timeIntervalSinceDate:startTime] >= 19 ) { if(roundf([[NSDate date] timeIntervalSinceDate:startTime]) == 20) { NSLog(@"First Time Location Update"); latitudeLongitude.text = [[ NSString alloc] initWithFormat:@"%g , %g", tempNewLocation.coordinate.latitude, tempNewLocation.coordinate.longitude]; float interval = [[NSDate date] timeIntervalSinceDate:startTime]; int okInterval = roundf(interval); NSLog(@"Interval 1 , %d", okInterval ); time.text = [[ NSString alloc] initWithFormat:@"%d", okInterval - 20]; speed.text = @"0"; totalDistance = 0; distance.text = @"0 meters"; } else { latitudeLongitude.text = [[ NSString alloc] initWithFormat:@"%g , %g", tempNewLocation.coordinate.latitude, tempNewLocation.coordinate.longitude]; float interval = [[NSDate date] timeIntervalSinceDate:startTime]; int okInterval = roundf(interval); time.text = [[ NSString alloc] initWithFormat:@"%d", okInterval - 20]; NSLog(@"Interval 2 , %d , %f", okInterval , interval); if((tempNewLocation.coordinate.latitude == tempOldLocation.coordinate.latitude && tempNewLocation.coordinate.longitude == tempOldLocation.coordinate.longitude) || tempNewLocation.speed = 0) totalDistance += [tempNewLocation distanceFromLocation:tempOldLocation] - (tempNewLocation.horizontalAccuracy / 2); else totalDistance += [tempNewLocation distanceFromLocation:tempOldLocation]; if (totalDistance < 0) distance.text = @"0 meters"; else distance.text = [[ NSString alloc] initWithFormat:@"%g meters", totalDistance]; } MKPointAnnotation *pa = [[MKPointAnnotation alloc] init]; pa.coordinate = tempNewLocation.coordinate; [map addAnnotation:pa]; [wayPoints addObject:tempNewLocation]; MKMapPoint * pointsArray = malloc(sizeof(CLLocationCoordinate2D)*2); pointsArray[0]= MKMapPointForCoordinate(tempOldLocation.coordinate); pointsArray[1]= MKMapPointForCoordinate(tempNewLocation.coordinate); routeLine = [MKPolyline polylineWithPoints:pointsArray count:2]; free(pointsArray); if (tempNewLocation.coordinate.latitude - tempOldLocation.coordinate.latitude < 1) { [map addOverlay:routeLine]; } } } @endHere is the source code for the project. Tracker Source Code