How to Determine Location in iPhone

Introduction

In this article I will create a Single View application. Here I use a map view from xib and write code for implementing an annotation pin. In this article we can find location in a map by providing a location name in the text field of an iPhone.

To understand it we use the following procedure.

Step 1

Open Xcode by double-clicking on it.

Step 2

Create a New XCode Project by clicking on it.

Step 3

Now Select Single View Application and click on Next.

Step 4

Now provide your Product Name and Company Identifier.

Step 5

Select the location where you want to save your project and click on Create.

Step 6

First we add the framework MkMapkit which is required to show the location.

Here we add one more framework, CoreLocation, which is required to search location by location name.

To import this framework we use the following.

Step 7

Click on project and select Build Phase.

Step 8
Click on the "+" icon to add a framework.

Step 9

Now we add both frameworks and click on the add button.

Step 10

Now we write the code.

AppDelegate.h

//

// mapAppDelegate.h

// test loaction

//

// Created by Sachin Bhardwaj on 10/01/13.

// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import <UIKit/UIKit.h>

@class mapViewController;

@interface mapAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) mapViewController *viewController;

@end


AppDelegate.m

//

// mapAppDelegate.m

// test loaction

//

// Created by Sachin Bhardwaj on 10/01/13.

// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import "mapAppDelegate.h"

#import "mapViewController.h"

@implementation mapAppDelegate

- (void)dealloc

{

[_window release];

[_viewController release];

[super dealloc];

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

// Override point for customization after application launch.

self.viewController = [[[mapViewController alloc] initWithNibName:@"mapViewController" bundle:nil] autorelease];

self.window.rootViewController = self.viewController;

[self.window makeKeyAndVisible];

return YES;

}

- (void)applicationWillResignActive:(UIApplication *)application

{

// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

}

- (void)applicationDidEnterBackground:(UIApplication *)application

{

// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

}

- (void)applicationWillEnterForeground:(UIApplication *)application

{

// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

}

- (void)applicationDidBecomeActive:(UIApplication *)application

{

// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

}

- (void)applicationWillTerminate:(UIApplication *)application

{

// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

}

@end

ViewController.h

//

// mapViewController.h

// test loaction

//

// Created by Sachin Bhardwaj on 10/01/13.

// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import <UIKit/UIKit.h>

#import <MapKit/MapKit.h>

@interface mapViewController : UIViewController<MKMapViewDelegate>

{

IBOutlet UITextField *addressField;

IBOutlet UIButton *goButton;

IBOutlet MKMapView *mapView;

}

@end

ViewController.m

//

// mapViewController.m

// test loaction

//

// Created by Sachin Bhardwaj on 10/01/13.

// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import "mapViewController.h"

#import "AddressAnnotation.h"

#import <MapKit/MapKit.h>

@interface mapViewController ()

@end

@implementation mapViewController

- (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

}

- (IBAction) showAddress {

//Hide the keypad

[addressField resignFirstResponder];

MKCoordinateRegion region;

MKCoordinateSpan span;

span.latitudeDelta=0.2;

span.longitudeDelta=0.2;

CLLocationCoordinate2D location = [self addressLocation];

region.span=span;

region.center=location;

AddressAnnotation *addAnnotation = [[AddressAnnotation alloc] init];

if(addAnnotation != nil) {

[mapView removeAnnotation:addAnnotation];

[addAnnotation release];

addAnnotation = nil;

}

addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];

[mapView addAnnotation:addAnnotation];

[mapView setRegion:region animated:TRUE];

[mapView regionThatFits:region];

}

-(CLLocationCoordinate2D) addressLocation {

NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",

[addressField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];

NSArray *listItems = [locationString componentsSeparatedByString:@","];

double latitude = 0.0;

double longitude = 0.0;

if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {

latitude = [[listItems objectAtIndex:2] doubleValue];

longitude = [[listItems objectAtIndex:3] doubleValue];

}

else {

//Show error

}

CLLocationCoordinate2D location;

location.latitude = latitude;

location.longitude = longitude;

return location;

}

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{

MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];

annView.pinColor = MKPinAnnotationColorGreen;

annView.animatesDrop=TRUE;

annView.canShowCallout = YES;

annView.calloutOffset = CGPointMake(-5, 5);

return annView;

}

- (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

ViewController.xib

ViewController.Xib-in-iPhone.png

AddressAnnotation.h

//

// AddressAnnotation.h

// test loaction

//

// Created by Sachin Bhardwaj on 11/01/13.

// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import <Foundation/Foundation.h>

#import <MapKit/MapKit.h>

@interface AddressAnnotation : NSObject <MKAnnotation> {

CLLocationCoordinate2D coordinate;

NSString *mTitle;

NSString *mSubTitle;

}

@end

AddressAnnotation.m

//

// AddressAnnotation.m

// test loaction

//

// Created by Sachin Bhardwaj on 11/01/13.

// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import "AddressAnnotation.h"

@implementation AddressAnnotation

@synthesize coordinate;

- (NSString *)subtitle{

return @"Here is I am";

}

- (NSString *)title{

return @"Hey!!";

}

-(id)initWithCoordinate:(CLLocationCoordinate2D) c{

coordinate=c;

NSLog(@"%f,%f",c.latitude,c.longitude);

return self;

}

@end

Step 11

Click on the Run button to show output.

Step 12

Output1 in iPhone:

Output1-in-iPhone.png

Output2 in iPhone:

Output2-in-iPhone.png

Now we provide the location name that we want to determine in the map.

Output3 in iPhone:

Output3-in-iPhone.png

After clicking on the search button we will see the location in the map.

Output4 in iPhone:

Output4-in-iPhone.png

Output5 in iPhone:

Output5-in-iPhone.png

When we click on "Pin" the message will be displayed.