MapKit Implementation in iOS

Posted By : Ashish Tyagi | 29-Jul-2014



MapKit framework allow the developer to easily integrateGPS Capability in their application and widely used to show annotations on a map. Annotation is like a pin which mark the specific location on map.

Here , we are getting the current location coordinate and address of user and also showing their location on mapview.

 

Getting User current location:

Step 1.) Create a new Project using Single view Application Template using storyboard. set navigation controller as a initial view Controller.

 

Step 2.) Create three textField(latitude,longitude and address) and two Button(get current location and show current location on map view) on view controller.

 

Step3.) Now ,create a new file “MapViewController” and set a destination view Controller as shown in screenshot.

 

 

Step 4.) Create reference outlet of all UIControls and import #import <CoreLocation/CoreLocation.h> in viewController.h file. Now replace the code of viewController.m file with following code.

 - (void)viewDidLoad
{
    [super viewDidLoad];
    self.title =@"MapKitDemo";
    locationManager = [[CLLocationManager alloc] init];
    geocoder = [[CLGeocoder alloc] init];
}

- (IBAction)getCurrentLocation:(id)sender {
    
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    CLLocation *currentLocation = newLocation;
    
    if (currentLocation != nil) {
        self.longitudeTextField.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
        self.latitudeTextField.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
    }
    
    [locationManager stopUpdatingLocation];
    //--Reverse Geocoding
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        
        if (error == nil && [placemarks count] > 0) {
            placemark = [placemarks lastObject];
            self.addressTextField.text = [NSString stringWithFormat:@"%@",
                                 placemark.country];
            NSLog(@"country is :::%@", placemark.country);

        } else {
            NSLog(@"%@", error.debugDescription);
        }
    } ];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"switchToMap"]) {

        MapViewController *mapViewController = segue.destinationViewController;
        mapViewController.latitude = self.latitudeTextField.text;
        mapViewController.longitude = self.longitudeTextField.text;
        NSLog(@"latitude is %@",mapViewController.latitude);
    }
}

        

a.) CLLocationManager is a class which is used for getting current location coordinate and didUpdateToLocation is their delegate method which is called every second when user location is changed or not . we are stop the calling of their delegate method after getting coordinate other it continuously consume battery power.

b.) prepareForSegue Method is used to pass the coordinate from viewController to mapViewController and “switchToMap” is the segue identifier which you have to set in storyboard.

c.) Reverse Geocoding is used to convert location coordinate into human readable form or address string.

 

Step 5.) Create NSObject type class named as Annotation.h and Annotation.m and replace their code as given bellow :

//----Annotation.h
#import <Foundation/Foundation.h>
#import <MapKit/MKAnnotation.h>

@interface Annotation : NSObject{

    CLLocationCoordinate2D coordinate;
	NSString *title;
	NSString *subtitle;
}

@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@end

 

Step 6.) Now in mapViewController , create two NSString type property of latitude and longitude and add the following code in MapViewController.m file.

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self showAnnotationOnMapView];
}

-(void)showAnnotationOnMapView{

    [self.mapView setMapType:MKMapTypeStandard];
	[self.mapView setZoomEnabled:YES];
	[self.mapView setScrollEnabled:YES];
	MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
	region.center.latitude = [self.latitude doubleValue];
	region.center.longitude = [self.longitude doubleValue];
	region.span.longitudeDelta = 0.01f;
	region.span.latitudeDelta = 0.01f;
	[self.mapView setRegion:region animated:YES];
	
	[self.mapView setDelegate:self];
	
	Annotation *annotation = [[Annotation alloc] init];
	annotation.title = @"I am here ";
	annotation.coordinate = region.center;
	[self.mapView addAnnotation:annotation];
}
-(MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:
(id )annotation {
	MKPinAnnotationView *annotationPinView = nil;
	if(annotation != self.mapView.userLocation)
	{
		static NSString *defaultPinID = @"annotation";
		annotationPinView = (MKPinAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
		if ( annotationPinView == nil ) annotationPinView = [[MKPinAnnotationView alloc]
										  initWithAnnotation:annotation reuseIdentifier:defaultPinID];
        
		annotationPinView.pinColor = MKPinAnnotationColorRed;
		annotationPinView.canShowCallout = YES;
		annotationPinView.animatesDrop = NO;
    }
	else {
		[self.mapView.userLocation setTitle:@"I am here"];
	}
	return annotationPinView;
}

        

On running application , When user click on “Get current Location” button then their current location coordinate and address will shown in respective TextField as shown in screenshot . User have to click on “Show current location on Map” to see a annotation pin on their location in map.

 

 

If you want to know more about MapKit Framework then go for apple developer documentation on Map and download sample code for above MapKit Implementation.

 

Hope it is useful for you :)

Aashish Tyagi

[email protected]

 

About Author

Author Image
Ashish Tyagi

Ashish is a iPhone application developer with experience in Objective-C , Titanium and Phonegap frameworks. Ashish loves watching movies in his free time.

Request for Proposal

Name is required

Comment is required

Sending message..