Tuesday, June 16, 2009

Display directions from the current location as starting address using Google Maps in iPhone programming

This article explains how to get the directions from the current location as the starting address using Google Maps in iPhone programming. Import the CoreLocation API in the iPhone application and create a UIViewController, a Webview and use the following code

// MapsWebViewController.h file
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface MapsWebViewController : UIViewController {
   IBOutlet UIWebView *mapsWebView;
    IBOutlet UIView *loadingView;
    NSString *contactAddress;
    float latitude;
    float longitude;
}

@property (nonatomic, retain) NSString *contactAddress;
@property (nonatomic, retain) NSString *displayDirections;
@property (nonatomic) float latitude;
@property (nonatomic) float longitude;

@end


// MapsWebViewController.m file

#import "MapsWebViewController.h"

@implementation MapsWebViewController

@synthesize contactAddress;
@synthesize latitude, longitude;

- (void)viewDidLoad {

    self.title = contactAddress;
    mapsWebView.scalesPageToFit = YES;
    contactAddress = [contactAddress stringByReplacingOccurrencesOfString:@" " withString:@","];
    contactAddress = [contactAddress stringByAppendingFormat:@",%@", @<Destination-Address>];
    NSString *theURLString = nil;

    theURLString = [NSString stringWithFormat: @"http://maps.google.com/maps?saddr=%f,%f&daddr=%@",
latitude, longitude,
[contactAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSURL *theURL = [NSURL URLWithString:theURLString];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:theURL];
    [mapsWebView loadRequest:theRequest];
    mapsWebView.userInteractionEnabled = YES;
    self.view.userInteractionEnabled = YES;
    [super viewDidLoad];
}

- (void)webViewDidStartLoad:(UIWebView *)webView {

    [self.view addSubview:loadingView];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {

    [loadingView removeFromSuperview];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError*)error {

    NSString *ErrorMessage = error.localizedDescription;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:ErrorMessage
delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];

   [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

}

- (void)didReceiveMemoryWarning {

   [super didReceiveMemoryWarning];
}

- (void)dealloc {

   [super dealloc];
}

@end

No comments:

Post a Comment