iOS 6 より前
現在の場所を取得するには Core Location を使用する必要がありますが、その緯度/経度のペアを使用すると、Maps を使用してそこから住所または場所までルートを表示できます。そのようです:
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]];
最後に、CoreLocation を使用して現在の場所を明示的に検索することを避け、@"http://maps.google.com/maps?saddr=Current+Location&daddr=%@"
代わりに URLを使用する場合は、 Current+Location文字列をローカライズする方法について、以下のコメントで提供したこのリンクを参照してください。ただし、文書化されていない別の機能を利用しているため、Jason McCreary が以下で指摘しているように、将来のリリースでは確実に機能しない可能性があります。
iOS 6 のアップデート
当初、マップは Google マップを使用していましたが、現在は Apple と Google が別々のマップ アプリを提供しています。
1) Google マップ アプリを使用してルートを指定する場合は、comgooglemaps URL スキームを使用します。
NSString* url = [NSString stringWithFormat: @"comgooglemaps://?daddr=%@&directionsmode=driving",
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
BOOL opened = [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
2) Apple Maps を使用するにはMKMapItem
、iOS 6 の新しいクラスを 使用できます。こちらの Apple API ドキュメントを参照してください。
基本的に、宛先座標( 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];
同じコードで iOS 6+ と iOS 6 より前の両方をサポートするには、Apple がMKMapItem
API doc ページに持っている次のようなコードを使用することをお勧めします。
Class itemClass = [MKMapItem class];
if (itemClass && [itemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)]) {
// iOS 6 MKMapItem available
} else {
// use pre iOS 6 technique
}
これは、Xcode Base SDK が iOS 6 (または最新の iOS )であることを前提としています。