Launch Maps from your iPhone app

Maps Application allows you to view and search Google Maps, see traffic reports, satellite views, get directions from one location to another. Launching Maps application from your own iPhone application can be done with one line of code:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

First you get a reference to your app from UIApplication class, and then you provide URL which will be opened in the Maps application. If you want just to show one location your URL should have this form:

NSString *googleUrl=[NSString stringWithFormat:@"http://maps.google.com/maps?ll=%f,%f", destinationCoordinate1, destinationCoordinate2];

If you want to get directions from one coordinate to another use this form:

NSString *url=[NSString stringWithFormat:@"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f", startCoordinate1, startCoordinate2, destinationCoordinate1, destinationCoordinate2];

You can notice the difference. First one uses ll (latitude and longitude), the other uses saddr (source address) and daddr (destination address). You can find more details on supported parameters in official Apple documentation.

For getting coordinates from an address you can use this method:

- (void) getLocationFromAddress:(NSString*)address
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

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

NSError *error = nil;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSUTF8StringEncoding error:&error];

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];

location.latitude = latitude;
location.longitude = longitude;
}

[pool release];
}

Image 2.

Image 2. Maps Application