从iOS应用程序中打开苹果地图应用并获取方向指引。

24
如标题所述,我希望在我的应用程序内通过按一个按钮来打开iOS设备中的原生地图应用程序。目前,我已经使用了一个MKMapView来显示从JSON文件中获取的纬度/经度的简单标记。
以下是代码:
- (void)viewDidLoad {
    [super viewDidLoad]; 
}


// We are delegate for map view
self.mapView.delegate = self;

// Set title
self.title = self.location.title;

// set texts...
self.placeLabel.text = self.location.place;


self.telephoneLabel.text = self.location.telephone;
self.urlLabel.text = self.location.url;


**// Make a map annotation for a pin from the longitude/latitude points
MapAnnotation *mapPoint = [[MapAnnotation alloc] init];
mapPoint.coordinate = CLLocationCoordinate2DMake([self.location.latitude doubleValue], [self.location.longitude doubleValue]);
mapPoint.title = self.location.title;**

// Add it to the map view
[self.mapView addAnnotation:mapPoint];

// Zoom to a region around the pin
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(mapPoint.coordinate, 500, 500);
[self.mapView setRegion:region];

当您点击图钉时,会出现一个带有标题和信息按钮的信息框。

这是代码:

    #pragma mark - MKMapViewDelegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    MKPinAnnotationView *view = nil;
    static NSString *reuseIdentifier = @"MapAnnotation";

    // Return a MKPinAnnotationView with a simple accessory button
    view = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIdentifier];
    if(!view) {
        view = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
        view.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        view.canShowCallout = YES;
        view.animatesDrop = YES;
    }

    return view;
}

我想创建一个方法,当在信息框中点击按钮时,打开地图应用程序并显示从当前用户位置到上方的地图点的路线。这种做法可能吗?还可以自定义该按钮的外观吗?(我是指像放置不同的图像到按钮上,使其看起来像“按我获取方向”那样)。

抱歉,如果这是一个愚蠢的问题,但这是我第一个iOS应用程序,Obj-c是一门全新的语言对我来说。

提前感谢所有回复。


请查看此链接 - https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html - nswamy
1
类似的问题已经在这里得到了回答:https://dev59.com/m2_Xa4cB1Zd3GeqP7P3M - Basheer_CAD
3个回答

48

这是打开地图应用并获取路线的代码:

Objective-C 代码

NSString* directionsURL = [NSString stringWithFormat:@"http://maps.apple.com/?saddr=%f,%f&daddr=%f,%f",self.mapView.userLocation.coordinate.latitude, self.mapView.userLocation.coordinate.longitude, mapPoint.coordinate.latitude, mapPoint.coordinate.longitude];
if ([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: directionsURL] options:@{} completionHandler:^(BOOL success) {}];
} else {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: directionsURL]];
}

使用mapPoint指定您要导航的位置。

适用于Swift3或更高版本

let directionsURL = "http://maps.apple.com/?saddr=35.6813023,139.7640529&daddr=35.4657901,139.6201192"
guard let url = URL(string: directionsURL) else {
    return
}
if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(url)
}

请注意,saddrdaddr 是位置名称或位置坐标的URL编码字符串(有关URL编码,请参见此处)。

directionsURL 示例:

// directions with location coordinate
"http://maps.apple.com/?saddr=35.6813023,139.7640529&daddr=35.4657901,139.6201192"
// or directions with location name
"http://maps.apple.com/?saddr=Tokyo&daddr=Yokohama"
// or directions from current location to destination location
"http://maps.apple.com/?saddr=Current%20Location&daddr=Yokohama"

更多选项参数(如传输类型、地图类型等)请参见此处


自iOS6以来,它将是maps.apple.com(虽然maps.google.com可能也可以工作!但苹果不想破坏东西)。无论如何,我认为最好使用迈克尔提到的API。 - Daij-Djan
我尝试过这个。我在我的详细视图中的按钮上添加了一个-(IBAction)。地图应用程序打开,但我收到一条消息“无法提供方向”。我使用了这段代码:- (IBAction)navigate{ NSString* url = [NSString stringWithFormat:@"http://maps.apple.com/maps?saddr=%f,%f&daddr=%f,%f",self.mapView.userLocation.coordinate.latitude, self.mapView.userLocation.coordinate.longitude, self.location.latitude, self.location.longitude]; [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]]; } - Kostenko
实际上它起作用了,但我需要将%f更改为%@。非常感谢! - Kostenko
1
很棒的答案,可以通过短信或邮件发送位置信息。 - Frank Eno
1
运行良好。但要注意Current%20Location应该只有一个百分号,否则URL将无法正确解析。 - Anton Ogarkov
显示剩余2条评论

17
您可以使用以下代码打开带有方向的地图:(假设您的id<MKAnnotation>类具有名为“coordinate”的CLLocationCoordinate2D公共属性)
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:[annotation coordinate] addressDictionary:nil];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:"WhereIWantToGo"]];
NSDictionary *options = @{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving};
[mapItem openInMapsWithLaunchOptions:options];

您也可以更改按钮,实际上您正在使用标准样式的按钮:

[UIButton buttonWithType:UIButtonTypeDetailDisclosure];

但你可以使用图像或标签为你的自定义按钮分配资源:

[[UIButton alloc] initWithImage:[UIImage imageNamed:"directionIcon.png"]];

9

这里是在苹果地图上显示方向的可行代码。它适用于从当前位置到目的地的路线,您只需要传递目的地的纬度和经度。

double destinationLatitude, destinationLongitude;
destinationLatitude=// Latitude of destination place.
destinationLongitude=// Longitude of destination place.

Class mapItemClass = [MKMapItem class];

if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)])
{
    // Create an MKMapItem to pass to the Maps app
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(destinationLatitude,destinationLongitude);
    MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil];

    MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
    [mapItem setName:@"Name/text on destination annotation pin"];

    // Set the directions mode to "Driving"
    // Can use MKLaunchOptionsDirectionsModeDriving instead
    NSDictionary *launchOptions = @{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving};

    // Get the "Current User Location" MKMapItem
    MKMapItem *currentLocationMapItem = [MKMapItem mapItemForCurrentLocation];

    // Pass the current location and destination map items to the Maps app
    // Set the direction mode in the launchOptions dictionary
    [MKMapItem openMapsWithItems:@[currentLocationMapItem, mapItem] launchOptions:launchOptions];
}

此外,如果您发现任何问题或我们需要找到另一种完成方法,请在此与我分享。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接