Show Location On Map Using Table in iPhone

Introduction

In this article I will create a Single View application. Here we add one more view from Cocoa Touch for implementing a map and add one more Objective-C class for implementing an annotation pin. In the first view here we add a table from outlet. In another view a map on delegate event of the table view or a notation pin on a particular location (that is passed by table) is shown.

To better understand 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 that is required to show the location.

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

At last click on the "Add" button to import the framework into the project.

framework-in-iPhone.png

Step 10

Now we write the code.

mapAppDelegate.h

//
// mapAppDelegate.h
// TableMap
//
// Created by Sachin Bhardwaj on 19/01/13.
// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.
//

#import <UIKit/UIKit.h>
@class mapViewController;
@interface mapAppDelegate : UIResponder <UIApplicationDelegate>
{
UINavigationController *nav;
}
@property (strong, nonatomic) UINavigationController *nav;
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) mapViewController *viewController;
@end

mapAppDelegate.m

//
// mapAppDelegate.m
// TableMap
//
// Created by Sachin Bhardwaj on 19/01/13.
// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.
//

#import "mapAppDelegate.h"
#import "mapViewController.h"
@implementation mapAppDelegate
@synthesize nav;
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[mapViewController alloc] initWithNibName:@"mapViewController" bundle:nil];
nav=[[UINavigationController alloc]initWithRootViewController:_viewController];
self.window.rootViewController=nav;
[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, inalidate 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

mapViewController.h
//
// mapViewController.h
// TableMap
//
// Created by Sachin Bhardwaj on 19/01/13.
// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "locationViewController.h"
@interface mapViewController : UIViewController
{
IBOutlet UITableView *table;
NSMutableArray *loaction;
NSMutableArray *name;
NSArray *imgplace;
}
@property (nonatomic,strong) UITableView *table;
@property (nonatomic,strong) NSMutableArray *loaction;
@property (nonatomic,strong) NSArray *imgplace;
@property (nonatomic,strong) NSMutableArray *name;
@end

ViewController.m

//
// mapViewController.m
// TableMap
//
// Created by Sachin Bhardwaj on 19/01/13.
// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.
//

#import "mapViewController.h"
@interface mapViewController ()
@end
@implementation mapViewController
@synthesize table,loaction,imgplace,name;
- (void)viewDidLoad
{
[super viewDidLoad];
//array=[[NSArray alloc]init];
self.loaction = [NSMutableArray arrayWithObjects:@"New Delhi", @"Jaipur", @"Bangalore", @"Mumbai", nil];
// imgplace=[[NSArray alloc]init];
imgplace = [NSArray arrayWithObjects:@"New Delhi.jpg", @"Jaipur.jpeg", @"Bangalore.jpeg", @"Mumbai.jpeg", nil];
self.name = [NSMutableArray arrayWithObjects:@"Nikhil",@"Sachin",@"Sajid",@"Rahul",nil];
self.title=@"City Name's";
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{//#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{//#warning Incomplete method implementation.
// Return the number of rows in the section.
return [self.loaction count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil){
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// cell.textLabel.text=[self.array objectAtIndex:[indexPath row]];
// UIImage *cellImage = [UIImage imageNamed:@"Audi.jpg"];
// cell.imageView.image = cellImage;
cell.textLabel.text = [NSString stringWithFormat:@"%@,%@",[self.name objectAtIndex:indexPath.row],[self.loaction objectAtIndex:indexPath.row]];
cell.imageView.image = [UIImage imageNamed:[imgplace objectAtIndex: indexPath.row]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"working");
locationViewController *my = [[locationViewController alloc] init];
my.strpath =[loaction objectAtIndex:indexPath.row];
[self.navigationController pushViewController:my animated:YES];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end

locationViewController.h

//
// locationViewController.h
// TableMap
//
// Created by Sachin Bhardwaj on 19/01/13.
// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <MapKit/Mapkit.h>
@interface locationViewController : UIViewController <MKMapViewDelegate>
{
IBOutlet MKMapView *mapView;
NSString *strpath;
}
@property (nonatomic,strong)IBOutlet MKMapView *mapView;
@property (nonatomic,strong) NSString *strpath;
-(CLLocationCoordinate2D) addressLocation;
@end

locationViewController.m

//
// locationViewController.m
// TableMap
//
// Created by Sachin Bhardwaj on 19/01/13.
// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.
//

#import "locationViewController.h"
#import "AddressAnnotation.h"

@interface locationViewController ()
@end
@implementation locationViewController
@synthesize strpath,mapView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
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] initWithCoordinate:location];
if(addAnnotation != nil) {
[mapView removeAnnotation:addAnnotation];
}
[mapView addAnnotation:addAnnotation];
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
NSLog(@"load");
}
-(CLLocationCoordinate2D) addressLocation
{
// NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",
//[addressField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// NSString *strLoction;
// strLoction=@"New Delhi";
NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",
[strpath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"urlString:%@",urlString);
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]encoding:NSUTF8StringEncoding error:nil];
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
NSLog(@"Error");
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
return location;
// Do any additional setup after loading the view from its nib.
}
- (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)viewDidUnload
{
[super viewDidUnload];}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end

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

Output3 in iPhone:

Output3-in-iPhone.png

Output4 in iPhone:

Output4-in-iPhone.png

Up Next
    Ebook Download
    View all
    Learn
    View all