从带有方向的 ios 应用程序打开苹果地图应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21983559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:33:36  来源:igfitidea点击:

Opens apple maps app from ios app with directions

iosiphoneobjective-cmapsapple-maps

提问by Kostenko

As the title states I would like to open the native maps app in the ios device from within my own app, by pressing a button. currently I have used an MKmapviewthat displays a simple pin with lat/long taken from a jsonfile.

正如标题所述,我想通过按下按钮从我自己的应用程序中打开 ios 设备中的本机地图应用程序。目前我使用了一个MKmapview显示一个简单的针脚,从json文件中获取纬度/经度。

the code is this :

代码是这样的:

- (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];

}`

}`

When you touch the pin an info box appears with a title and an info button.

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

this is the code :

这是代码:

    #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;
}

I want to make a method that opens the maps app with directions from the Current users location to the mapPoint above , when clicking the button in the info box above. Is that possible? Also Can I customize the look of this button? (i mean like putting a different image to the button to make it look like "press me for direction kinda" ).

我想创建一个方法,当单击上面信息框中的按钮时,可以打开地图应用程序,其中包含从当前用户位置到上面 mapPoint 的方向。那可能吗?我也可以自定义这个按钮的外观吗?(我的意思是在按钮上放一个不同的图像,使它看起来像“按我的方向”)。

Sorry if this a stupid question, but this is my first ios app and Obj-c is a totally new language to me.

对不起,如果这是一个愚蠢的问题,但这是我的第一个 ios 应用程序,而 Obj-c 对我来说是一种全新的语言。

thanks for all the replies in advance.

感谢您提前回复。

回答by larva

You init a button and add action to button:

您初始化一个按钮并向按钮添加操作:

Objective-C Code

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]];
}

with the mapPoint is where you want to direction to.

与 mapPoint 是你想要的方向。

Swift3 or later

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)
}

Note that saddr, daddris urlencodedstring of location name or location coordinate (about encode URL look at here).

请注意,saddr,daddr是位置名称或位置坐标的urlencoded字符串(关于编码 URL 看这里)

directionsURLexample:

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"

More options parameters (like transport type, map type ...) look at here

更多选项参数(如传输类型、地图类型...)请看这里

回答by Micha?l Azevedo

You can open maps with direction using this code : (assuming your id< MKAnnotation > class has a CLLocationCoordinate2D public property named "coordinate")

您可以使用以下代码打开带方向的地图:(假设您的 id< MKAnnotation > 类具有名为“坐标”的 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];

You can also change the button, actually you are using a standard style button :

您还可以更改按钮,实际上您使用的是标准样式按钮:

[UIButton buttonWithType:UIButtonTypeDetailDisclosure];

But you can alloc your custom button with an image or a label :

但是您可以使用图像或标签分配自定义按钮:

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

回答by anshul-systematix

Here is the working code for showing directions on Apple map. It'll work for current place to your destination place and you just need to pass lat & long of destination place.

这是在 Apple 地图上显示路线的工作代码。它适用于当前地点到您的目的地,您只需要通过目的地的纬度和经度。

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];
}

Also, share me here, if notice any issue or we need to find out another way to done it.

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