从代码打开地图应用程序 – 在哪里/如何find“当前位置”?
我正在打开地图应用程序,以显示从用户的当前位置到目标坐标的方向,从我的代码。 我正在使用下面的代码来打开地图应用程序。 我按下button时调用此代码。 getCurrentLocation
是返回最近更新的位置的方法。
- (void)showDirectionsToHere { CLLocationCoordinate2D currentLocation = [self getCurrentLocation]; // LINE 1 NSString* url = [NSString stringWithFormat: @"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f", currentLocation.latitude, currentLocation.longitude, destCoordinate.latitude, destCoordinate.longitude]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]]; }
这里LINE 1中的 [self getCurrentLocation]
使用CLLocationManager
来确定当前位置并返回值。
注意 :我还没有在LINE1中实现代码。 我刚刚计划这样做。
我的问题是:
- 这是在地图应用程序被调用时计算当前位置的好习惯吗?
- 在
openURL
被调用之前,[self getCurrentLocation
]会返回当前位置? - 在打开地图应用程序之前,我必须确定当前位置吗?
我对这些事情有点困惑。 请引导我。 谢谢。
您不必自己确定用户的当前位置,地图应用程序将负责处理。
而不是传递一个纬度/经度对,你可以通过Current%%20Location
和地图将决定用户的当前位置本身。
%20
是一个url编码的空格字符,额外的%
转义了实际的%
所以它不会被解释为格式replace。
感谢@Carlos P在原始答案中指出我的转义字符错误。
使用“当前位置”作为saddr只有当用户的系统语言设置为英语时才起作用。 最好的select是从核心位置获取当前位置,并将其作为saddr使用。
正如pazustep指出的,“当前位置”仅适用于英语。 例如在意大利语中,正确的string是“Posizione attuale”。
在iPhone固件嗅探我检测到所有的“当前位置”翻译,我写了一个类,提供任何(当前)支持的语言所需的正确的string。
在我的博客上有一篇关于这个(包括源代码)的文章: http : //www.martip.net/blog/localized-current-location-string-for-iphone-apps 。
您可以为iOS 6使用新的MKMapItem
类。 请参阅Apple API文档
基本上,如果路由到目标坐标 ( destCoordinate
),你将使用类似这样的东西:
MKPlacemark* place = [[MKPlacemark alloc] initWithCoordinate: destCoordinate 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 )。
在这个其他答案中,我提供了一个强大的iOS 5.1及更低版本的技术