Friday, February 27, 2009

Mapping Directions from your App

If you want to give your user driving directions by launching the Maps application, it's actually pretty easy. You just create a regular Google Maps URL and use UIApplication to open it up; Your phone will recognize that the URL is for directions and will open Maps.app rather than Safari.app automatically.

The URL format is very easy for directions:

http://maps.google.com/maps?saddr=[source address or coordinates]&daddr=[destination address or coordinates]

Here is an example of taking the coordinates pulled from Core Location, and using that as the starting point for directions:

    NSString *destinationString = @"Cupertino,California";
NSString *url = [NSString stringWithFormat: @"http://maps.google.com/maps?saddr=%f,%f&daddr=%@", newLocation.coordinate.latitude, newLocation.coordinate.longitude, destinationString];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

Of course, this doing this quits your application and launches Maps.app, so make sure you've got everything saved before you do it.

There is one gotcha if you're using search terms or a physical address instead of coordinates. Maps.app doesn't like spaces. Unlike Safari, Maps.app won't automatically convert spaces to %20 for you. On the other hand, you don't want to use NSString's stringByAddingPercentEscapesUsingEncoding: either, because that method will convert commas, dashes, and certain other characters, which may cause problems when launching Maps.app (and probably will - those commas are important!).

In most cases, you can just remove the spaces by doing this:

    NSString *newAddressPartOfURL = [addressPartOfURL stringByReplacingOccurrencesOfString:@" " withString:@""]

Technically speaking, we're cheating. We should be able to URL-encode the whole address no problem, and it should work. But… it doesn't. This is one of those situations where you need to cheat a little to get things to work properly. I can tell you from first-hand experience that if you URL-encode those commas in your address, you will get a message that Maps.app couldn't find the specified address.

No comments:

Post a Comment