Invoke map app in iOS app
最近在写个app,要调地图来展示一个地点,于是就有了三种选择:ios5之前的, 装了gmap的ios6和没装gmap的,在网上转了转,拼出来下面一段代码:
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@“comgooglemaps://"]]) { // iOS 6 with google map app installed NSString *loc_path = [[NSString alloc] initWithFormat: @“comgooglemaps://?center=%f,%f”, lat, lng]; NSURL *loc_url = [NSURL URLWithString:loc_path]; [[UIApplication sharedApplication] openURL:loc_url]; } else { // Check whether it is iOS 6 Class mapItemClass = [MKMapItem class]; if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)]) { CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(lat, lng); MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil]; MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark]; [mapItem setName:venue_name];
[mapItem openInMapsWithLaunchOptions:nil];
} else {
// Early than iOS 6
NSString *loc_path = [[NSString alloc] initWithFormat: @"http://maps.google.com/maps?ll=%f,%f", lat, lng];
NSURL *loc_url = [NSURL URLWithString:loc_path];
[[UIApplication sharedApplication] openURL:loc_url];
}
}
逻辑很简单,首先判断是否可以打开gmap app的[URL schema](https://developers.google.com/maps/docum entation/ios/urlscheme),如果不行则试着创建iOS 6新加入的MKMapItem,如果不能打开,则就是老的iOS了。因为只需要打开系统内建的map程序,所以就这样啦。
PS: MKMapItem那段程序是从网上找到的,嗯。