我知道可以通过在带有位置字符串的参数 saddr
和 daddr
的谷歌地图 URL 上调用 openURL
来启动 iPhone map 应用程序或纬度/经度(参见下面的示例)。
但我想知道是否可以将起始地址设为 “当前位置” map 书签,以便我可以使用 map 应用的位置处理代码。我的 Google 搜索毫无结果。
例如:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat: @"http://maps.google.com/maps?saddr=%@&daddr=%@", myLatLong, latlong]]];
除了调用当前位置书签来代替 myLatLong
。
最佳答案
iOS 6 之前
您需要使用核心位置来获取当前位置,但使用该纬度/经度对,您可以让 map 将您从那里路由到街道地址或位置。像这样:
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=%@ "
网址,然后是 see this link that I provided in comments below了解如何本地化 Current+Location 字符串。但是,您正在利用另一个未记录的功能,正如 Jason McCreary 在下面指出的那样,它在未来的版本中可能无法可靠地工作。
iOS 6 更新
最初,Maps 使用 Google map ,但现在,Apple 和 Google 拥有独立的 map 应用程序。
1) 如果您想使用 Google map 应用程序进行路线规划,请使用 the comgooglemaps URL scheme :
NSString* url = [NSString stringWithFormat: @"comgooglemaps://?daddr=%@&directionsmode=driving",
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
BOOL opened = [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
2) 要使用 Apple map ,您可以使用适用于 iOS 6 的新 MKMapItem
类。See the Apple API docs here
基本上,如果路由到目的地坐标 (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)。
关于ios - 如何调用 iPhone map 以获取当前位置作为起始地址的方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/576768/