这是官方的Apple方式:
Class mapItemClass = [MKMapItem class];
if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)])
{
CLLocationCoordinate2D coordinate =
CLLocationCoordinate2DMake(16.775, -3.009);
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinate
addressDictionary:nil];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:@"My Place"];
[mapItem openInMapsWithLaunchOptions:nil];
}
如果您想获取到该位置的驾车或步行路线指示,您可以在
+openMapsWithItems:launchOptions:
中的数组中包含一个带有
MKMapItem
的
mapItemForCurrentLocation
,并适当设置启动选项。
Class mapItemClass = [MKMapItem class];
if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)])
{
CLLocationCoordinate2D coordinate =
CLLocationCoordinate2DMake(16.775, -3.009);
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinate
addressDictionary:nil];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:@"My Place"];
NSDictionary *launchOptions = @{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeWalking};
MKMapItem *currentLocationMapItem = [MKMapItem mapItemForCurrentLocation];
[MKMapItem openMapsWithItems:@[currentLocationMapItem, mapItem]
launchOptions:launchOptions];
}
在一个if
语句后的else
语句中,可以保留原始iOS 5及以下版本的代码。请注意,如果您颠倒openMapsWithItems:
数组中项目的顺序,则会获得从坐标点到当前位置的方向。您可以通过传递一个构建的MKMapItem
而不是当前位置地图项来使用它来获取任意两个位置之间的方向。我没有尝试过。
最后,如果您有一个地址(作为字符串)想要获取方向,请使用地理编码器通过CLPlacemark
创建一个MKPlacemark
。
Class mapItemClass = [MKMapItem class];
if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)])
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:@"Piccadilly Circus, London, UK"
completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *geocodedPlacemark = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc]
initWithCoordinate:geocodedPlacemark.location.coordinate
addressDictionary:geocodedPlacemark.addressDictionary];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:geocodedPlacemark.name];
NSDictionary *launchOptions = @{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving};
MKMapItem *currentLocationMapItem = [MKMapItem mapItemForCurrentLocation];
[MKMapItem openMapsWithItems:@[currentLocationMapItem, mapItem] launchOptions:launchOptions];
}];
}