iOS 6 之前的版本
您需要使用核心位置来获取当前位置,但是通过该纬度/经度对,您可以让地图将您从那里路由到街道地址或位置。就像这样:
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,然后请参阅我在下面的评论中提供的链接 http://www.martip.net/blog/localized-current-location-string-for-iphone-apps了解如何本地化当前+位置细绳。但是,您正在利用另一个未记录的功能,正如 Jason McCreary 在下面指出的那样,它在未来的版本中可能无法可靠地工作。
iOS 6 更新
起初,Maps使用谷歌地图,但现在,苹果和谷歌有单独的地图应用程序。
1)如果您想使用 Google 地图应用程序进行路线规划,请使用comgooglemaps URL 方案 https://developers.google.com/maps/documentation/ios/urlscheme#directions:
NSString* url = [NSString stringWithFormat: @"comgooglemaps://?daddr=%@&directionsmode=driving",
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
BOOL opened = [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
2)要使用 Apple 地图,您可以使用新的MKMapItem
iOS 6 的类。请参阅此处的 Apple API 文档 https://developer.apple.com/documentation/mapkit/mkmapitem
基本上,如果路由到目的地,您将使用类似的东西坐标 (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文档页面:
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).