Pre iOS 6
Du må bruke Core-posisjon for å få den nåværende posisjon, men med det lat / lang pair, kan du få kart til ruten du derfra, til en gateadresse eller sted. Som så:
CLLocationCoordinate2D currentLocation = [self getCurrentLocation];
// this uses an address for the destination. can use lat/long, too with %f,%f format
NSString* address = @"123 Main St., New York, NY, 10001";
NSString* url = [NSString stringWithFormat: @"http://maps.google.com/maps?saddr=%f,%f&daddr=%@",
currentLocation.latitude, currentLocation.longitude,
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
Til slutt, hvis du ønsker å unngå å bruke CoreLocation eksplisitt finne det aktuelle stedet, og ønsker å bruke @"http://maps.google.com/maps?saddr=Current+Location&daddr=%@"url i stedet, så se denne linken som jeg ga i kommentarene under for hvordan du kan lokalisere Nåværende + Location streng. Men er du drar nytte av en annen udokumentert funksjon, og som Jason McCreary påpeker nedenfor, kan det ikke fungere pålitelig i fremtidige utgivelser.
Oppdatering for iOS 6
Opprinnelig Maps brukte Google maps, men nå, Apple og Google har egne kart apps.
1) Hvis du ønsker å ruten ved hjelp av Google Maps app, bruker den comgooglemaps URL-ordningen :
NSString* url = [NSString stringWithFormat: @"comgooglemaps://?daddr=%@&directionsmode=driving",
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
BOOL opened = [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
2) For å bruke Apple Maps, kan du bruke den nye MKMapItemklassen for iOS 6. Se Apples API docs her
I utgangspunktet vil du bruke noe sånt som dette, hvis ruting til bestemmelses koordinater ( latlong):
MKPlacemark* place = [[MKPlacemark alloc] initWithCoordinate: latlong addressDictionary: nil];
MKMapItem* destination = [[MKMapItem alloc] initWithPlacemark: place];
destination.name = @"Name Here!";
NSArray* items = [[NSArray alloc] initWithObjects: destination, nil];
NSDictionary* options = [[NSDictionary alloc] initWithObjectsAndKeys:
MKLaunchOptionsDirectionsModeDriving,
MKLaunchOptionsDirectionsModeKey, nil];
[MKMapItem openMapsWithItems: items launchOptions: options];
For å støtte både iOS 6+ og pre iOS 6 i den samme koden, vil jeg anbefale å bruke noe sånt som dette kode som Apple har på MKMapItemAPI doc siden:
Class itemClass = [MKMapItem class];
if (itemClass && [itemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)]) {
// iOS 6 MKMapItem available
} else {
// use pre iOS 6 technique
}
Dette vil anta at Xcode Base SDK er iOS 6 (eller siste iOS ).